问题描述
我想为特定格式创建日期,例如2010年3月20日的日期为mdY格式,但date函数无法理解该日期并返回错误的日期
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"));
以上代码返回错误的日期,其背后的原因是什么,以及如何避免错误的结果?我希望日期函数识别的几种格式是 Y / m / d, m / d / Y, F d,Y, M d,Y。
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".
推荐答案
strtotime无法识别以'-'分隔的美式风格,但是如果使用'/'分隔符,它将很好用。
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")));
如Pekka所言,最好是代码明确声明使用的格式。
As Pekka notes, it's better if your code explicity declares the format you are using.
这篇关于日期时间从格式创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!