简体   繁体   中英

Get the “Right” Year of a Certain Date with PHP DateTime

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM