解决PHP的date函数”YW”参数自然周BUG

官方的文档是记录了这个bug的,只会在计算1年的第一周和最后一周会有错误。

Things to be aware of when using week numbers with years.

<?php
echo date(“YW”, strtotime(“2011-01-07”)); // gives 201101
echo date(“YW”, strtotime(“2011-12-31”)); // gives 201152
echo date(“YW”, strtotime(“2011-01-01”)); // gives 201152 too 这里就会有问题
?>

BUT

<?php
echo date(“oW”, strtotime(“2011-01-07”)); // gives 201101
echo date(“oW”, strtotime(“2011-12-31”)); // gives 201152
echo date(“oW”, strtotime(“2011-01-01”)); // gives 201052 (Year is different than previous example)
?>

Reason:
Y is year from the date
o is ISO-8601 year number
W is ISO-8601 week number of year

Conclusion:
if using ‘W’ for the week number use ‘o’ for the year.

找php手册帮忙http://www.php.net/manual/zh/function.date.php 里面就有详细介绍

要注意哦!

此条目发表在开源代码分类目录,贴了, 标签。将固定链接加入收藏夹。

发表回复