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

前端 未结 2 481
野性不改
野性不改 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 20:46

    Hm, average difference in seconds, why that PHP swath of code if your database can give it to you:

    SELECT 
      SEC_TO_TIME(MAX(TIME_TO_SEC(TIMEDIFF(end_time,start_time)))) AS max_timediff,
      SEC_TO_TIME(MIN(TIME_TO_SEC(TIMEDIFF(end_time,start_time)))) AS min_timediff,
      SEC_TO_TIME(AVG(TIME_TO_SEC(TIMEDIFF(end_time,start_time)))) AS avg_timediff,
      SEC_TO_TIME(SUM(TIME_TO_SEC(TIMEDIFF(end_time,start_time)))) AS sum_timediff,
      COUNT(id) as total_events
    FROM atb_log 
    WHERE 
      siteID=:siteID 
      AND start_time > :fromDate
      AND end_time < :toDate
    

    Format those min/max/avg/sum of seconds as you like.

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题