Reputation: 9763
I am trying to calculate dates relative to a certain date, but Im getting some very unusual responses. Can someone explain what I am doing wrong? I am US EST if it matters.
<?php
$firstweek_firsttime = date('D M j', strtotime("June 2016 first Sunday"));//June 19th 2016
$firstweek_lasttime = date('D M j', strtotime("June 2016 second Saturday"));
$ret=array(
"Session #1. The week of ".$firstweek_firsttime." to ".$firstweek_lasttime." - ",
"Session #2. The week of ".date('D M j', strtotime("$firstweek_firsttime next Sunday"))." to ".date('D M j', strtotime("$firstweek_lasttime next Saturday"))." - ",
"Session #3. The week of ".date('D M j', strtotime("$firstweek_firsttime +10 day"))." to ".date('D M j', strtotime("$firstweek_lasttime +10 day"))." - "
);
?>
<ul>
<?php
foreach($ret as $wk)
{
?>
<li><?php echo($wk);?></li>
<?php
}
?>
What I am getting:
The week of Sun Jun 19 to Sat Jun 18 -
The week of Thu Jan 1 to Thu Jan 1 -
The week of Wed Jul 1 to Tue Jun 30 -
Goal:
The week of Sun Jun 19 to Sat Jun 25 -
The week of Sun Jun 26 to Sat Jul 2 -
The week of Sun Jul 3 to Sat Jul 9 -
Upvotes: 1
Views: 41
Reputation: 7310
This works for me.
Where "you" are has no bearing on your dates unless you set your timezone. The date/time is set based on the server location.
It's a bit cumbersome, if I can find a better method I'll update my answer.
UPDATE
strtotime("$firstweek_firsttime");
is the equivalent of writing strtotime("Sun Jun 5");
will output 1433635200 (which, as of today, is actually Sun Jun 7 2015 00:00:00) because no year is indicated, the server defaults to the current year
strtotime("next sunday");
will output 1441497600 (which, as of today, is equal to Sun Sep 6 2015 00:00:00
but
strtotime("$firstweek_firsttime next sunday");
is invalid markup and will output nothing
so, since the timestamp is empty the date is automatically set to Jan 1, 1970
The same goes for strtotime("$firstweek_lasttime next Saturday")
strtotime("$firstweek_firsttime +10 days")
is the same as strtotime("Sun Jun 5 +10 days")
without a Year the server defaults to the current year and writes it as strtotime("Sun Jun 7 2015 +10 days")
because June 7 is the first Sunday for June in 2015
The same goes for strtotime("$firstweek_lasttime +10 day")
All that being said... the simple solution to your question is adding the year to your date format for $firstweek_firsttime and $firstweek_lasttime. This will keep your date in the year that you expect like so...
<?php
$firstweek_firsttime = date('D M j Y', strtotime("June 2016 first Sunday")); // Sun Jun 5 2016
$firstweek_lasttime = date('D M j Y', strtotime("June 2016 second Saturday"));
If you don't want to output the year to the browser simply change your first array item to...
"Session #1. The week of ".date('D M j', strtotime("$firstweek_firsttime"))." to ".date('D M j', strtotime("$firstweek_lasttime"))." - ",
Reference
Upvotes: 1