问题
I have a pagination function which pages through a time table and advances the dates on a weekly basis and displays the details relevant to the new dates.
Whilst testing some new data I encountered a paging problem. In that it would not page passed 22/10/2012.
Debugging the code I eventually found the source of the problem which is that incrementing the date stamp representing 22/10/2012 by 7 days returned (via strftime) a date of 28/10/2012 when obviously I was expecting a date of the 29/10/2012. This error effectively causing a continuous loop as %W (which drives the weekly pagination) is 43 for 22/10/2012 and 43 for 28/10/2012 and of course it should be 44 for 29/10/2012.
In a quick test to isolate and recreate this problem I used the following:
/*
* test %W
*/
$time_Stamp_1 = mktime(0,0,0,10,22,2012);
echo "date : " . strftime("%d/%m/%Y", $time_Stamp_1);
echo "W for first time stamp " . $time_Stamp_1 . " is " . strftime("%W", $time_Stamp_1);
$time_Stamp_1a = $time_Stamp_1 += (60 * 60 * 24 * 7);
echo "new date : " . strftime("%d/%m/%Y", $time_Stamp_1a);
echo "W for new date time stamp: " . strftime("%W", $time_Stamp_1a);
$time_Stamp_2 = mktime(0,0,0,10,29,2012);
echo "W for second time stamp: " . strftime("%W", $time_Stamp_2);
The pagination happily moves between all the other weeks I have tested and obviously uses this increment / decrement as appropriate.
Hopefully I am missing something obvious. Any thoughts?
回答1:
The PHP DateTime class is the way to go:-
$inFormat = 'd/m/Y h:i';
$outFormat = 'd/m/Y';
$date = DateTime::createFromFormat($inFormat, '22/10/2012 00:00');
$interval = new DateInterval('P7D');
for($i = 0; $i < 10; $i++){
$date->add($interval);
var_dump($date->format($outFormat) . " is in week " . $date->format('W'));week');
}
Gives the following output:-
string '29/10/2012 is in week 44' (length=24)
string '05/11/2012 is in week 45' (length=24)
string '12/11/2012 is in week 46' (length=24)
string '19/11/2012 is in week 47' (length=24)
string '26/11/2012 is in week 48' (length=24)
string '03/12/2012 is in week 49' (length=24)
string '10/12/2012 is in week 50' (length=24)
string '17/12/2012 is in week 51' (length=24)
string '24/12/2012 is in week 52' (length=24)
string '31/12/2012 is in week 01' (length=24)
Which, a quick glance at a calendar tells me, is correct.
See here for valid format strings http://us.php.net/manual/en/datetime.createfromformat.php
Also see the DateInterval class.
See here for valid output formats for DateTime::format() http://us.php.net/manual/en/function.date.php
回答2:
Or better yet use DateTime.
// Create the DateTime object
$date = new DateTime('2012-22-10');
echo $date->format('d/m/Y');
// Add one week
$date->modify('+1 week');
echo $date->format('d/m/Y');
回答3:
Try using strtotime() for time calculations - e.g. to get the next week use:
$time_Stamp_1a = strtotime("+1 week", $time_Stamp_1);
来源:https://stackoverflow.com/questions/12511325/php-incrementing-time-stamp-error