Getting Dates From Week Numbers in PHP
Recently I’ve been building a little project that pulls data from Google Analytics and shows your web statistics in a simple form. One thing I wanted to do was show the data for a quarter, but graphing by day is too chaotic and graphing by month only gives three points, so I wanted to graph by week. This was fine but the data returned by Analytics only gives me the week numbers, and since this project is aimed at demystifying web stats for normal people, it really needs normal dates on it!
Using DateTime::setISODate
I found that the DateTime extension has a method setISODate() which accepts the year and week number, and makes a date you can then use as normal.
$week_start = new DateTime();
$week_start->setISODate($year,$week_no);
echo $week_start->format('d-M-Y');
You can also do this the other way around; if you have a date in PHP, there’s the ‘W’ flag for date() which will return you the week number – very handy!
Interesting discovery!
DateTime class can be really helpful. Recently I have used diff() method to calculate distance between two dates with DateInterval.
Nice and simple dolution. Thanks for the great help.
The DateTime class is fabulous – it is a nice interface to essentially complicated problems. It annoys me though that so few people seem to use it.
Hello, nice article. I am new in php so could you please explain how can i do this the other way around. Because if i understood correctly i cannot do it with “method setISODate()”. I tried to add extra variable “date” but it didnt returned me a week. Thanks!
If you are creating a date by putting together a year and week number, then you would use the method above. To get the week number of a date, you can do DateTime::format (or just plain date()) and use the ‘W’ as the format.
You helped me alot with this snippet… Been messing with finding months from a week number :).
Solved thanks to you!
Thanks
Just thanks for this simple way of getting that date
Perfect this was just what I was looking for! :)
Thx, for this clean and short solution!
Thanks for this clear solution.
Thanks, very useful!
Why is this nowhere on the php docs? I’m adding it.
so cool, easy way to do it. Thanks
Helped me alot with this. I have been struggling with finding dates from a week number a long time (at least almost a hole day) .
You are my hero now :-D