使用 PHP DateTime 获取特定日期的 "Right" 年

Get the "Right" Year of a Certain Date with PHP DateTime

我试图将日期 "YYYY/MM/DD" 转换为 "YYYY/WW" 格式,因此我可以存储每周聚合数据,其结构如下

aggre_date(YYYY/WW)    value    id

但是我发现了一个讨厌的问题

$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

有什么方法可以改进我的每周聚合数据设计或获得 "right" 年吗?

您需要使用 o 作为 ISO 年份:

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

Demo