DateTime::add adds hours even when interval should only be seconds

前端 未结 2 522
野性不改
野性不改 2021-01-24 20:34

This comes from my previous question on getting the average time interval over a specified data set, [located here][1]. I\'ll post the entire function again:

fun         


        
2条回答
  •  庸人自扰
    2021-01-24 21:01

    As I wrote in the answer to your other question, this is a DST (Daylight Savings Time) problem. In the U.S., DST has already begun; in Europe not.

    Try this code:

    timecheck("Europe/Amsterdam");
    timecheck("America/Los_Angeles");
    
    function timecheck($timezone) {
    date_default_timezone_set($timezone);
    
    $totalATB=new DateTime("@0");
    $t1 = "2014-01-01 17:30:00";
    $t2 = "2014-01-01 17:35:00";
    
    $dt1 = new DateTime($t1);
    $dt2 = new DateTime($t2);
    
    $timeDiff = date_diff($dt1, $dt2, true);
    
    printf("[%s] Starting with with: %s\n", $timezone, $totalATB->format("H:i:s"));
    $totalATB->add($timeDiff);
    printf("[%s] added %s, total is now: %s\n", $timezone, $timeDiff->format("%H:%I:%S"), $totalATB->format("H:i:s"));
    }
    

    The output:

    [Europe/Amsterdam] Starting with with: 00:00:00
    [Europe/Amsterdam] added 00:05:00, total is now: 00:05:00
    [America/Los_Angeles] Starting with with: 00:00:00
    [America/Los_Angeles] added 00:05:00, total is now: 01:05:00
    

提交回复
热议问题