问题描述
似乎很多人在PHP中遇到日期/时间问题,并且不可避免地,许多被接受的答案往往是功能。 DateTime对象使代码更加易读,避免了使用60 * 60 * 24进行整个Unix时间戳修改来提前日期。
I'll start off by saying that I am a big advocate for using the DateTime object, which allows you to use the DateTime::createFromFormat()
function. The DateTime object makes the code much more readable and avoids the need to do the whole Unix timestamp modification using 60 * 60 * 24 to advance the date days.
这就是说,strtotime()采用的任意字符串不是很难预测。 列出了支持的格式。
That being said, the arbitrary string that strtotime() takes is not very hard to predict. Supported Date and Time Formats lists the formats that are supported.
根据您无法区分MM / DD / YYYY和DD / MM / YYYY的示例,它根据。使用斜杠的日期总是以美式格式读取。所以00/00/0000格式的日期将永远读为MM / DD / YYYY。或者使用破折号或周期将是DMY。例如00-00-0000将永远读为DD-MM-YYYY。
As per your example of not being able to differentiate between MM/DD/YYYY and DD/MM/YYYY it does differentiate based on the Date Formats. Dates that use slashes are always read as American format. So a date in the format 00/00/0000 will always be read as MM/DD/YYYY. Alternatively using dashes or periods will be DMY. e.g. 00-00-0000 will always be read as DD-MM-YYYY.
以下是一些示例:
<?php
$dates = array(
// MM DD YYYY
'11/12/2013' => strtotime('2013-11-12'),
// Using 0 goes to the previous month
'0/12/2013' => strtotime('2012-12-12'),
// 31st of November (30 days) goes to 1st December
'11/31/2013' => strtotime('2013-12-01'),
// There isn't a 25th month... expect false
'25/12/2013' => false,
// DD MM YYYY
'11-12-2013' => strtotime('2013-12-11'),
'11.12.2013' => strtotime('2013-12-11'),
'31.12.2013' => strtotime('2013-12-31'),
// There isn't a 25th month expect false
'12.25.2013' => false,
);
foreach($dates as $date => $expected) {
assert(strtotime($date) == $expected);
}
正如你可以看到几个关键的例子是 25/12/2013
和 12.25.2013
如果读取相反的格式,则它们都有效,但是返回 false
,因为它们根据排除的日期和时间格式无效...
As you can see a couple of key examples are 25/12/2013
and 12.25.2013
which would both be valid if read the with the opposite format, however they return false
as they are invalid according the the Suported Date and Time Formats...
所以你可以看到行为是相当可预测的。一如以往,如果您从使用输入收到日期,您应该首先验证该输入。如果您没有首先验证输入,则方法不起作用。
So as you can see the behaviour is quite predictable. As always if you are receiving a date from use input you should be validating that input first. No method will work if you are not validating the input first.
如果您想要非常具体地了解正在阅读的日期,或者您所提供的格式, t支持的格式,那么我建议使用 DateTime :: createFromFormat()
。
If you want to be very specific about the date being read, or the format you are being given isn't a supported format, then I recommend using DateTime::createFromFormat()
.
这篇关于strtotime()认为有害吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!