Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - How to get year, month, day from time string

Tags:

Given the following timestring:

$str = '2000-11-29';  $php_date = getdate( $str ); echo '<pre>'; print_r ($php_date); echo '</pre>'; 

How to get the year/month/day in PHP?

[seconds] => 20 [minutes] => 33 [hours] => 18 [mday] => 31 [wday] => 3 [mon] => 12 [year] => 1969 [yday] => 364 [weekday] => Wednesday [month] => December [0] => 2000 

I don't know why I get 1969 for year.

Thank you

like image 316
q0987 Avatar asked Aug 31 '10 03:08

q0987


People also ask

How can I get the date of a specific day with PHP?

You can use the date function. I'm using strtotime to get the timestamp to that day ; there are other solutions, like mktime , for instance.

How can I get current date and time in PHP?

Answer: Use the PHP date() Function You can simply use the PHP date() function to get the current data and time in various format, for example, date('d-m-y h:i:s') , date('d/m/y H:i:s') , and so on.


2 Answers

You can use strtotime to parse a time string, and pass the resulting timestamp to getdate (or use date to format your time).

$str = '2000-11-29';  if (($timestamp = strtotime($str)) !== false) {   $php_date = getdate($timestamp);   // or if you want to output a date in year/month/day format:   $date = date("Y/m/d", $timestamp); // see the date manual page for format options       } else {   echo 'invalid timestamp!'; } 

Note that strtotime will return false if the time string is invalid or can't be parsed. When the timestamp you're trying to parse is invalid, you end up with the 1969-12-31 date you encountered before.

like image 166
Daniel Vandersluis Avatar answered Sep 22 '22 13:09

Daniel Vandersluis


PHP - How to get year, month, day from time string

$dateValue = strtotime($q);                       $yr = date("Y", $dateValue) ." ";  $mon = date("m", $dateValue)." ";  $date = date("d", $dateValue);  
like image 31
Pradeep Bhaskar Avatar answered Sep 18 '22 13:09

Pradeep Bhaskar