Recently I had to work with weekly calenders in a PHP project and was surprised how easy PHP makes it for you to handle different date formats - especially the things you often need, but never know, like the current calender week.
No typing "which week of the year is it?" into your searchbar; just do: date('W')
.
And in case you need to determine the number of weeks in a year, there's this snippet:
date('W', mktime(0, 0, 0, 12, 28, 2026))
.
It basically calculates the week of the year of the 28th December and will basically return 52 or 53. Yep, some years have 53 weeks, but every last day of a year will have December 28, come what may.
So, how many weeks do we have left this year?
date('W', mktime(0, 0, 0, 12, 28, 2022)) - date('W')
For working with weekly calenders it might be useful to retrieve the date of the the first day of the week. PHP's strtotime()
function is really helpful here. Depending on what you consider the first day of the week, you can call for example:
date('Y-m-d', strtotime("Monday this week"))
.
These relative time formats can also be extended, which is quite helpful - for example when you need to determine which date was the Wednesday 5 weeks ago when the new Cronenberg movie premiered here:
date('Y-m-d', strtotime("Wednesday this week -5 weeks"))
.
And you can work with calender weeks in absolute formats, too:
date('Y-m-d', strtotime("2022-W47-1"))
.
This gives you the date of the 1st day of the 47th week of 2022.
Keep in mind that it depends on your locale which weekday is considered the first day of the week. You can change that locally or in your ini.
Top comments (0)