Date Time create from format

人盡茶涼 提交于 2019-12-11 02:24:51

问题


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


回答1:


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.




回答2:


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");



回答3:


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]));


来源:https://stackoverflow.com/questions/3542162/date-time-create-from-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!