获得“正确”使用PHP DateTime的特定日期的年份 [英] Get the "Right" Year of a Certain Date with PHP DateTime
问题描述
我正在尝试将日期YYYY / MM / DD转换为YYYY / WW格式,因此我可以存储每周聚合数据,其结构如下
I was trying to transform a date "YYYY/MM/DD" into "YYYY/WW" format, so I can store the weekly aggregation data, which has a structure below
aggre_date(YYYY/WW) value id
但我发现一个讨厌的问题
But I found a nasty problem
$dateTime = new DateTime("2014-12-30");
echo $dateTime->format("Y-W")."\n";
$dateTime = new DateTime("2014-01-01");
echo $dateTime->format("Y-W")."\n";
结果完全相同 2014-01
,但前者应为 2015-01
。
The result is exactly same 2014-01
, but the former should be 2015-01
.
有没有办法改善我的每周聚合数据设计或获得正确年份?
Is there any way to improve my weekly aggregation data design or to get the "right" year?
推荐答案
您需要在ISO年期间使用 o
p>
You need to use o
for the ISO year:
ISO-8601年数。这与Y具有相同的值,除了如果ISO周数(W)属于上一年或下一年,则代替使用该年。 (添加PHP 5.1.0)
ISO-8601 year number. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. (added in PHP 5.1.0)
$dateTime = new DateTime("2014-12-30");
echo $dateTime->format("o-W")."\n";
$dateTime = new DateTime("2014-01-01");
echo $dateTime->format("o-W")."\n";
2015-01
2014-01
这篇关于获得“正确”使用PHP DateTime的特定日期的年份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!