问题
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";
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?
回答1:
You need to use o
for the ISO year:
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
来源:https://stackoverflow.com/questions/29909142/get-the-right-year-of-a-certain-date-with-php-datetime