• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 276
  • Last Modified:

PHP date problem

Hi, I have a small problem with dates.
I try to display a week in a small loop.
I start from one day, and add seven times one day. When I try this at the end of october, the result is not what I expect.

Here is a small exmaple program:

      1 <?php
      2     // Week 44 (end of october) in 2004
      3
      4     $date = 1099173600;
      5
      6     // display the whole week
      7     for ($i=0; $i<7; $i++)
      8     {
      9         echo (date ('Y-m-d', $date + ($i*24*60*60)));
     10         echo ('<br>');
     11     }
     12 ?>

And the output:

2004-10-31
2004-10-31
2004-11-01
2004-11-02
2004-11-03
2004-11-04
2004-11-05

The first and the second date appear to bet the same (although their integer representation isn't!)

Any help appreciated

Barry
0
barrel
Asked:
barrel
  • 4
  • 2
1 Solution
 
Diablo84Commented:
replace:

for ($i=0; $i<7; $i++)

with:

for ($i=1;$i<=7;$i++) {
0
 
Diablo84Commented:
eg:

$date = 1099173600;

for ($i=1;$i<=7;$i++) {
 echo (date ('Y-m-d', $date + ($i*24*60*60)));
 echo ('<br>');
 }

otherwise i in the first loop is 0 so the timestamp will be $date+0 basically... or in otherwords identical to the timestamp
0
 
Diablo84Commented:
Actually with your original code, i cannot recreate the output you show, this however is a better way of writing this:

<?php
$date = 1099173600;

for ($i=0;$i<7;$i++) {
 echo date('Y-m-d',strtotime("+$i days",$date))."<br>\n";
}
?>
0
Learn to develop an Android App

Want to increase your earning potential in 2018? Pad your resume with app building experience. Learn how with this hands-on course.

 
barrelAuthor Commented:
Hi,

Thanks for your _fast_ answer.
The fact that I start at zero is because I calculate the first day of the week which also needs to be displayed.

Your approach works for the specific date, but then I run into troubles when displaying a 'normal' week...

The fact that you cannot reproduce it makes me think that this is a PHP bug?

I am using version 4.3.4 by the way

Barry
0
 
barrelAuthor Commented:
Well... that did the trick.

No idea why simply adding it doesn't work and the "+$i days" does...:-/

Anyway, I am a happy man, I can continue... :-)
0
 
Diablo84Commented:
There are various issues that come up when working with timestamps and php, a lot of the time its related to DST (Daylight Savings time) which can throw it out an hour and hence produce the wrong stamp. When adding time in blocks of days, weeks, months etc its always best to use strtotime in my opinion because then it works around this problem.

Best Wishes

|)iablo
0

Featured Post

The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

  • 4
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now