Adding days to a timestamp

后端 未结 7 1252
春和景丽
春和景丽 2021-02-05 07:59

Giving a starting date, I\'m adding four times seven days to get 5 different dates separated exactly a week each one.

//$date = \'28-10-2010\';
$timestamp = mkti         


        
7条回答
  •  有刺的猬
    2021-02-05 08:33

    Never use math like 60*60*24*7 to add/subtract days (because of daylight time saving), use strtotime or mktime instead:

    $timestamp = strtotime('+7 days', $timestamp);
    
    // Or something like this (it's OK to have day parameter <= 0 or > 31)
    $timestamp = mktime(0, 0, 0, $month, $day + 7, $year);
    

    Your example will be more obvious if you'll output time as well:

    $timestamp = mktime(0, 0, 0, 10, 28, 2010);
    echo date('Y-m-d H:i:s', $timestamp) . "\n";
    
    $timestamp += 60*60*24*7;
    echo date('Y-m-d H:i:s', $timestamp) . "\n";
    

    Output:

    2010-10-28 00:00:00
    2010-11-03 23:00:00
    

    Here you have 2010-11-03 23:00:00 instead of 2010-11-04 00:00:00 because one of the days (31 Oct) is 25 hours long instead of 24.

提交回复
热议问题