Question

I want to create date with specific format for e.g 03-20-2010 have a format of m-d-Y but date function do not understand this date and returns wrong date

$date = date("Y-m-d", strtotime("03-20-2010"));

Above code is returning wrong date, what is the reason behind it and how to avoid wrong result? Few formats that I want date function to recognize are "Y/m/d" , "m/d/Y" , "F d, Y" , "M d, Y".

Was it helpful?

Solution

strtotime won't recognize an American style ordering separated by '-', but if you use a '/' separator, it will work just fine.

$date = date("Y-m-d", strtotime(str_replace('-', '/', "03-20-2010")));

As Pekka notes, it's better if your code explicity declares the format you are using.

OTHER TIPS

Funnily enough, your question title contains the exact solution to the problem!

Use DateTime::createFromFormat. (Note: Requires PHP >= 5.3)

It allows you to specify the exact format of the date to expect, so there is none of strtotime()s ambiguity / anglo-american bias.

This should work:

$date = DateTime::createFromFormat("Y-m-d", "2010-03-20");

you can get the timestamp with mktime and use that timestamp

$exact_time = "03-20-2010";
$exploded_et = explode("-",$exact_time);
$date = date("Y-m-d",mktime(0,0,0,$exploded_et[0],$exploded_et[1],$exploded_et[2]));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top