views:

47

answers:

3

Hi, 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".

A: 

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", "03-20-2010");
Pekka
Care to explain the downvote?
Pekka
This function is for php greater than 5.3 and it is giving undefined function error for my version.
Ayaz Alavi
well answer was pretty obvious since it was in documentation but it was not applicable for most of the web applications currently running.
Ayaz Alavi
@Ayaz fair enough, I overlooked the 5.3 limitation and that renders it indeed unusable on most shared hosters at the moment. It is still rude to downvote a (technically still valid) answer without any comment, especially if you're the question asker who is being helped. A question is never only for yourself, it's for future generations who face the same issue. I don't care about the downvote, but I do care about the gesture. It really isn't good style. If you want answers from me in the future, don't do it any more.
Pekka
thanks for your answer anyway.
Ayaz Alavi
+2  A: 

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.

Paul Dixon
thanks str_replace worked
Ayaz Alavi
+1  A: 

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]));
yasaluyari
I thought about that but is it applicable for all formats?
Ayaz Alavi