33 Votes

PHP: Wrong Year for first Calendar Week

Question by Compi | Last update on 2024-04-11 | Created on 2016-06-11

In PHP, it is possible to determine the calendar week (week number) using the function date() and the placeholder "W".

For example, this code should provide me with the current week number as a result:

echo 'week ', date('W', time()), ', ', date('Y', time());  

With time() I get the current time, with "W" I get the week number and with "Y" the year - the result should be something like "week 5, 2024".

However, unfortunately, this solution is not working for the case that the first calendar week is falling into the old year or the last calendar week is falling into the new year. For example, 2016-01-01 is resulting in "week 53, 2016" and not in "week 53, 2015" as expected - the year is always wrong in this transitional period.

What can I do, to make this function work also on December 31 and January 1?

ReplyPositiveNegative
2Best Answer2 Votes

When using "Y", the year always corresponds to the year of the date that you pass with the second parameter to the date() function. Therefore, for the calendar week number, there is the additional own placeholder "o" available.

So, you have to modify your code in the following way:

echo 'week', date('W', time()), ', ', date('o', time());

I have described more about that within my tutorial about how to determine the calendar week using PHP.
Last update on 2024-04-11 | Created on 2016-06-11

ReplyPositive Negative
Reply

Related Topics

PHP: Determine Week Number

Tutorial | 0 Comments

Android Getting Sound Levels

Open Question | 1 Answer

PHP: Current Date and Time

Tutorial | 0 Comments

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.