简体   繁体   中英

Date functions in PHP

Another simple question. I found this really cool snippet of code:

$date_str = "Jan 14th 2011";
$date = date_parse_from_format('M jS Y', $date_str);
echo $date->format('Y-m-d');

But when I run it on my computer it says Fatal error: Call to a member function format() on a non-object line 3.

The code was taken from here Converting date string to date so I presume it is good but it looks like it is referencing to an object that does not exist.

I have been looking at http://php.net/manual/en/function.date-parse-from-format.php and http://www.w3schools.com/php/php_ref_date.asp amongst many others but I have not found any any clues.

My question is should this code work as a standalone piece of code. If so why does it not work for me? Else, should I do to get it to work as expected.

date_parse_from_format();

returns associative array and you are trying to access the class method on a non object.

if you want to make use of PHP's inbuilt DateTime class. then more information here http://in2.php.net/manual/en/datetime.format.php

date_parse_from_format returns an array, not a DateTime object. What you want is

$date = date_create_from_format('M jS Y', $date_str);
             ^^^^^^---note the change
echo date('Y-m-d', $date);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM