PHP:解析任何格式的日期(特别是:2008-10-20、2008/10/20、2008.10.20、11月20/08)
strtotime("25/03/1957")
返回 false。什么可以满足所有这些日期格式?我无法想象真正制作自己的作品需要多长时间,所以我希望您已经知道了。
谢谢!
strtotime("25/03/1957")
returns false. what will satisfy all of these date formats? i can't imagine how long it would take to actually make my own, so i hope there's already one out there you know of.
thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
考虑到某些日期是有效的,但可以指向两个不同的实际日期,没有任何函数能够始终“猜测”正确的格式...
为了解决这个问题,在 PHP >= 5.3 中,添加了一个新函数添加:
date_create_from_format
- 但它没有PHP 不存在 < 5.3,不幸的是...(另请参阅
DateTime:: createFromFormat
)Still, in the example you took, the year 1957 is a possible source of problems : PHP generally works with [UNIX Timestamps][3], when it comes to dates...
而且,至少在 32 位系统上,这些只能表示 1970 年到 2038 年之间的日期——因为它们计算自 1970 年 1 月 1 日以来的秒数。
为了避免这个问题,通常最好使用
DateTime
类,其中 (引用):(它不会解决 PHP < 5.3 的解析问题;但它会解决日期范围问题...)
Considering some dates are valid but can point to two different actual dates, no function will ever be able to "guess" the right format at all times...
To help with that, with PHP >= 5.3, a new function has been added :
date_create_from_format
-- but it doesn't exist with PHP < 5.3, unfortunately...(See also
DateTime::createFromFormat
)Still, in the example you took, the year 1957 is a possible source of problems : PHP generally works with [UNIX Timestamps][3], when it comes to dates...
And, at least on 32-bits systems, those can only represent dates between 1970 and 2038 -- as they count the number of seconds since 1970-01-01.
To avoid this problem, it's often a good idea to use the
DateTime
class, with which (quoting) :(It will not solve the parsing problems with PHP < 5.3 ; but it'll solve the date-range problem...)
我发现 dateTime 对象支持比 strtotime() 函数更广泛的格式,并且服务器的时区设置也会产生影响;但我最终构建了一个函数,在使用字符串日期方法之前将“/”替换为“-”。我还测试是否有效,然后尝试交换明显的 dd 和 mm (25-03-2001 => 03-25-2001) 如果无效,然后再次测试。
I've found that dateTime objects support a wider range of formats than the strtotime() function, and the timezone settings of your server also make a difference; but I ended up building a function that would replace '/' with '-' before using the string to date methods. I also test for valid, then try swapping the apparent dd and mm (25-03-2001 => 03-25-2001) if invalid before testing again.