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

你。 提交于 2019-12-02 07:20:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!