使用序数值时 php strtotime 函数的问题 [英] Issue with php strtotime function when using ordinal values
问题描述
在 strtotime 中使用序数值时,我有时会得到意想不到的结果.例如,为什么
I sometime get unexpected results when using ordinal values with strtotime. For example, why does
date("M j", strtotime("second Tuesday February 2011"))
结果为2 月 15 日"(实际上是 2011 年的第三个星期二?
result in "Feb 15" (which is actually the third Tuesday in 2011?
推荐答案
看来依靠 strtotime 来处理序数日期计算是不安全的——至少在 PHP <5.3.(我已经用 5.2.9 和 5.2.11 进行了测试,尽管在线文档中声称该错误已在 5.2.7 中修复,但两者都不起作用.)
It seems that it's not safe to rely on strtotime to deal with ordinal date computations -- at least in versions of PHP < 5.3. (I've tested with 5.2.9 and 5.2.11 and neither works despite the claim in the online documentation that the bug was fixed in 5.2.7.)
按照建议添加of"显然仅适用于 php 5.3+ 并完全删除序数将返回第一次"出现,但其他序数将关闭 7 天.
Adding "of" as suggested apparently only works in php 5.3+ and dropping the ordinal altogether will return the "first" occurrence, but other ordinals will be 7 days off.
PHP 5.2 的最佳解决方案似乎是这样的:
The best solution for PHP 5.2 seems to be something like this:
$recurrOrdinal = "last";
$dayOfWeek = "Thursday";
$monthYear = "March 2011";
echo ordinalDate($recurrOrdinal, $dayOfWeek, $monthYear);
function ordinalDate($recurrOrdinal, $dayOfWeek, $monthYear) {
$firstDate = date("j", strtotime($dayOfWeek . " " . $monthYear) );
if ($recurrOrdinal == "first")
$computed = $firstDate;
elseif ($recurrOrdinal == "second")
$computed = $firstDate + 7;
elseif ($recurrOrdinal == "third")
$computed = $firstDate + 14;
elseif ($recurrOrdinal == "fourth")
$computed = $firstDate + 21;
elseif ($recurrOrdinal == "last") {
if ( ($firstDate + 28) <= date("t", strtotime($monthYear)) )
$computed = $firstDate + 28;
else
$computed = $firstDate + 21;
}
return date("Y-m-d", strtotime($computed . " " . $monthYear) );
}
这篇关于使用序数值时 php strtotime 函数的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!