PHP get the year from the variable - php

I usually mess this up, but I am trying to get a year from a variable $date = 2011-01-01 I am trying to get 2011 from the variable...I tried this but it didnt echo anything out...
date(strtotime("Y"), strtotime($date));

$year = date('Y', strtotime('2011-01-01'));
Or, if you don't want to convert to date, and trust your input format:
$year = explode('-', '2011-01-01')[0];
The above requires PHP 5.4, on older versions you need two lines:
$arr = explode('-', '2011-01-01');
$year = $arr[0];
Or yet, this slightly faster alternative suggested by tigrang:
$year = substr($date, 0, 4);
Or, an even faster way, as salathe suggested:
$year = (int) $date;
(everything after the first dash will be ignored, so $year will contain an integer with the year part of the date (unlike the other options, where $year would be a string).

date('Y', strtotime($date)) should do
First arg is the format, second is timestamp.

You can explode the date into a list and call each date item individually.
$date = '2012-01-01';
list($year, $month, $day) = explode('-', $date);
echo $year; // echoes 2012

May I suggest using PHP's DateTime class as an alternative:
$date = '2011-01-01';
$dateTime = new DateTime($date);
echo $dateTime->format('Y');

DateTime is all well and good, but lets go old school.
sscanf($date, '%d', $year);
// or
$year = strtok($date, '-');
// or
$year = substr($date, 0, 4);
// or
$year = (int) $date;
or, putting the sensible hat back on, you could use DateTime or correctly use date().
$datetime = new DateTime($date);
$year = $datetime->format('Y');
// or
$year = date('Y', strtotime($date));

Related

Fastest way to get month, day, year, from date string

I am getting a date from the mysql database:
here is what it comes out as:
2017-01-20
what would be the fastest way to get the month, day, and year, so for example, when i echo, it will be like this:
echo $month; //01
echo $day; //20
echo $year; //2017
Well, if you know that the output will consistently be a string in the format "YYYY-MM-DD", the most basic approach is:
<?php
$query = ... //query is your string "YYYY-MM-DD"
$year = substr($query, 0, 4);
$month = substr($query, 5, 2);
$day = substr($query, 8, 2);
echo $month;
echo $day;
echo $year;
?>
Let's assume you have that string in a variable called $date
$date = '2017-01-20';
You can explode it into a list if you are sure the format is consistent:
list($year, $month, $day) = explode("-", $date, 3);
You could convert the date to a time integer using strtotime to use in other functions like date. This has the added benefit of being able to test that this is a well-formed date:
$time = strtotime($date);
if ($time === false) die("Bad date format: $date.");
$year = date('Y', $time);
$month = date('m', $time); // 'n' if you don't want leading zero
$day = date('d', $time); // 'j' if you don't want leading zero
As jasonmoqio points out, since you asked for fastest, substr is a tiny bit faster than exploding. (On my workstation looping substr vs. explode 10 million times only produced an improvement of 1/1000th of a second over exploding, so unless this is in a loop that gets run millions of times, you will not notice the difference and should opt for code readability.)
$year = substr($date, 0, 4);
$month = substr($date, 5, 2);
$day = substr($date, 8, 2);
Try this:
$date = new DateTime('2017-01-20');
echo 'Year:'.$date->format("Y");
echo 'Month:'.$date->format("m");
echo 'Day:'.$date->format("d");
Output:
Year: 2017
Month: 01
Day: 20
If you want to quickly get the date from mysql, try using regex like this.
if (preg_match('/^(?P<year>\d+)[-\/](?P<month>\d+)[-\/](?P<day>\d+)$/', $your_date, $matches)) {
$mydate = $matches['year'] . "-" . $matches['month'] . "-" . $matches['day'];
$whatever = date('Y-m-d', strtotime($tgl));
// You can echo it...
// echo $matches['year'];
// echo $matches['month'];
// echo $matches['day'];
}
Hope this help you out. :D

Retrieve date, month, year from a date in php

I have this piece of code which gets me a field from the database:
$end_date=$row1['end_date'];
If i print it it gives me something like: 25-09-2012
What i need is to get the month value, the year and date.
something like:
$month=09;
$day=25;
$year=2012;
How can i do that?
thanks!
Using DateTime:
$date = new DateTime($row1['end_date']);
$year = $date -> format('Y');
$month = $date -> format('m');
$day = $date -> format('d');
If your timestamps are all like the one provided, keep it simple:
list($day, $month, $year) = explode('-', $row1['end_date']);
In your case, you can use the explode function like this :
// store a string containing "25-09-2012"
$end_date = $row1['end_date'];
// split "25-09-2012" into an array of three elements
$thedate = explode("-", $end_date);
// retrieve the values
$month = $thedate[0]; // 25
$day = $thedate[1]; // 09
$year = $thedate[2]; // 2012
try
[month('end_date')]
[day('end_date')]
[year('end_date')]
Or use explode and use - as the delimiter
Take a peak at this helpful tutorial describing various formatting methods and useful date functions in PHP:
Date/Time Functions
Date Formats
A. You can use DateTime
$date = DateTime::createFromFormat('d-m-Y',$row1['end_date']);
$month = $date->format("m");
$day = $date->format("d");
$year = $date->format("Y");
B. Using strtotime
$date = strtotime($row1['end_date']);
$month = date("m", $date);
$day = date("d", $date);
$year = date("Y", $date);
C. You can just sscanf scan through the string
$date = sscanf($row1['end_date'], "%d-%d-%d");
$month = $date[0] ;
$day = $date[1] ;
$year = $date[2] ;
D. Another method is using list & explode
list($day, $month, $year) = explode('-', $row1['end_date']);
Do it on a single line and format it however you would like. (Dec, December, 12) and so on with date().
list($month, $day, $year) = explode('-', date('m-d-Y', strtotime($row1['end_date'])));
$values = getdate(strtotime($row1['end_date']));
echo $values['mon']; //month
echo $values['mday']; //day
echo $values['year']; //year

conflict between implode function and strtotime

I have a problem in this code:
$month = $_POST['month'];
$day = $_POST['day'];
$year = $_POST['year'];
function dateImplodeFunction($year, $month, $day){
$array = array($year, $month, $day);
$date = date('Y-m-d', strtotime( implode("-", $array)));
return $date;
}
based on the code above I'm going to create a function where there are 3 inputs month, day and a year. When I input those 3 these variables will passed to this function, combine those 3 variables and use the implode function to create a format based on what date you specified. for instance let's say if I input 10/01/1989 it will echo the display 10/01/1989.
also I need to use date function together with strtotime function (refer to the code above) for database, setting my date field into date data type.
The problem here is if I input 10-01-1989, it returns/dipslays the value of 01-01-1970 why??
I figured it out that there is a conflict between strtotime and implode function due to test. I've search through google but it find none. I hope you can help me. Thanks in advance.
sorry for the bad english =P
I would just use the Date Time class.
$month = '07';
$day = '26';
$year = '2012';
$timezone = new DateTimeZone('America/New_York');
$date = new DateTime( "{$year}-{$month}-{$day}", $timezone );
print $date->format('Y-m-d H:i:s');
# Output: 2012-07-26 00:00:00
http://codepad.org/VxwDHPeU
You should use mktime :
function dateImplodeFunction($year, $month, $day)
{
return date('Y-m-d', mktime(0, 0, 0, $month, $day, $year));
}
Documentation of mktime here

convert a date in this format '031012' into a date that I can add days to

I have a date in this format 030512 (ddmmyy).
But I'm having trouble with converting this to a date usable format I can add days to.
Basically.. I extracted the date above from a text file, Now I need to be able to add a number of days to it. But I am having trouble parsing the date in this format.
Is there another way of doing this rather then something like this:
// I have a date in this format
$date = '030512'; // 03 May 2012
$day = substr($date,0,2);
$month = substr($date, 2,2);
$year = substr($date, 4,2);
$date_after = $day . "-" . $month . "-".$year;
// Now i need to add x days to this
$total_no_nights = 010; // must be this format
$days_to_add = ltrim($total_no_nights,"0"); // 10, remove leading zero
// how do i add 10 days to this date.
You can do this (php >= 5.3):
$date = DateTime::createFromFormat('dmy', '030512');
$date->modify('+1 day');
echo $date->format('Y-m-d');
http://www.php.net/manual/en/datetime.createfromformat.php
For php < 5.3 :
$dateArray = str_split('030512', 2);
$dateArray[2] += 2000;
echo date("d/m/Y", strtotime('+1 day', strtotime(implode('-', array_reverse($dateArray)))));
try this using the month/day/year you already have:
$date = "$month/$day/$year";
$change = '+10 day';
echo date("d/m/Y", strtotime($change, strtotime($date)));
Assuming the date will always be in the future (or at least after 1st Jan 2000), you're not far wrong:
// I have a date in this format
$date = '030512'; // 03 May 2012
$day = substr($date,0,2);
$month = substr($date, 2,2);
$year = substr($date, 4,2);
// dd-mm-yy is not a universal format but we can use mktime which also gives us a timestamp to use for manipulation
$date_after = mktime( 0, 0, 0, $month, $day, $year );
// Now i need to add x days to this
$total_no_nights = "010"; // must be this format
$days_to_add = intval( $total_no_nights ); // No need to use ltrim
// Here's the "magic". Again it returns a timestamp
$new_date = strtotime( "+$days_to_add days", $date_after );
Using the DateTime object would be easier but you say you're not on PHP5.3.
You can't do date manipulation with strings becase, well, they are not dates. In PHP, you can use Unix timestamps (which are actually integers...) or DateTime objects. In you case:
$timestamp = strtotime('-10 days', mktime(0, 0, 0, $month, $day, $year));
echo date('r', $timestamp);
... or:
$object = new DateTime("$year-$month-$day");
$object->modify('-10 days');
echo $object->format('r');
Also, please note that 010 is an octal number that corresponds to 8 in decimal.
using the convert function in sql the date can be obtained in appropriate format.
anter that operations can be performed in php to manipulate the date. i hope that answers your query.

problem to Get Date, month Year separately From database in Php File?

i want to separate date, month, time, hour, min ,sec getting from database, for count down timer,
in data base stored date is 2010/10/10:
me using this code :
$m=date('m',$row['Date']);
$d=date('d',$row['Date']);
output is month=31
date = 12....
If you want them separetely, you can use the explode function with list eg:
list($year, $month, $day) = explode('/', $row['Date']);
Also, you can use the strtotime function for getting individual values:
echo 'Day' . date('d', strtotime($row['Date']));
echo 'Month' . date('m', strtotime($row['Date']));
echo 'Year' . date('Y', strtotime($row['Date']));
$d = // Pull your date from the db
$date = new DateTime($d);
$day = $date->format('l'); // Creates day name
$day = $date->format('j') // Creates date number
$month = $date->format('n'); // Creates month number
$year = $date->format('Y'); // Creates year
..and so forth.
You can find formatting options here, http://php.net/manual/en/function.date.php

Categories