Reputation: 1554
I am constructing a diary that has weekly views which I thought I had cracked because the dates seemed to appears as correct. It wasn't until my MySQL queries kept returning what seemed like random results that I realized the the month is actually being seen as the day instead.
$week_number = date("W");
$year = date("Y");
for ($day=0; $day<=6; $day++) {
$daily_date = date('d/m/Y', strtotime($year."W".$week_number.$day))."\n";
$StartDate = date('d', strtotime($daily_date));
}
echo $starteDate;
$startDate
returns the number of the month rather than the day and sure enough date('m', strtotime($daily_date))
returns the day rather than the month.
I can't understand where I have made this silly mistake so any help would be appreciated.
Upvotes: 3
Views: 1896
Reputation: 3035
This is because of the Americanisation of dates - strtotime will read the date as m/d/Y rather than d/m/Y.
The ISO for dates is Y-m-d and for ease I would use this format when doing any kind of date manipulation.
Upvotes: 4
Reputation: 360622
That code is horrible. You're converting dates to strings multiple times. There is absolutely NO reason to take your $year . w. $week_number.etc...
value, convert it to a string, then convert that string back to a date just to extract the day value.
As well, d/m/Y is a horrible format to use for date transport, because... riddle me this, what is 01/02/03. Is that 3rd Feb 2001? 1 Mar 2002? If you can't figure it out, how can you expect strtotime to be better at it? it's fairly smart, but it's not omnicient, and it's DEFINITELY not infallible. A 4digit year does make it a bit easier, but you can still end up with d/m
v.s. m/d
confusion.
Why not simply
$StartDate = date('d', strtotime($year."W".$week_number.$day));
or better yet, use the DateTime class and select an appropriate DateInterval
Upvotes: 1