doucuo1642 2012-09-21 09:01
浏览 62
已采纳

如何比较自定义格式的两个时间戳?

I have two timestamps that are formated like this: substr( date( 'YmdHisu' ), 0, 17 )

20120921105240000
20120921115626000

Now, how do I compare them?

I tried to do a simple approach like:

$diff = abs( 20120921105240000 - 20120921115626000 );

But this doesn't give me the needed result, since the time messes it up. All I want to do, is find out, how many minutes( or seconds ) have passed between them.

Thanks in advance.

  • 写回答

3条回答 默认 最新

  • dporu02280 2012-09-21 09:06
    关注
    $date1 = DateTime::createFromFormat('Ymdhisu', '20120921105240000');
    $date2 = DateTime::createFromFormat('Ymdhisu', '20120921115626000');
    $interval = $date1->diff($date2);
    print_r($interval);
    
    /*DateInterval Object
    (
        [y] => 0
        [m] => 0
        [d] => 0
        [h] => 1
        [i] => 3
        [s] => 46
        [invert] => 0
        [days] => 0
    )*/
    
    $seconds = $date2->getTimestamp()-$date1->getTimestamp();
    echo $seconds;
    

    Example

    See extra info on the object and method.

    For PHP < 5.3:

    Method sscanf + mktime:

    $date1 = '20120921105240000';
    $date2 = '20120921115626000';
    
    function parse_mydate_string($string) {
        if ($a = sscanf($string, '%4s%2s%2s%2s%2s%2s') {
            if (FALSE !== $r = mktime($a[3], $a[4], $a[5], $a[1], $a[2], $a[0])) {
                return $r;
            }
        }
        throw new InvalidArgumentException('Not the expect date string.');
    }
    
    $diff    = parse_mydate_string($date1) - parse_mydate_string($date2);    
    $absdiff = abs($diff);
    

    or sscanf + vsprintf + strtotime:

    $date1 = '20120921105240000';
    $date2 = '20120921115626000';
    
    $date1 = vsprintf('%s-%s-%s %s:%s:%s', sscanf($date1, '%4s%2s%2s%2s%2s%2s'));
    $date2 = vsprintf('%s-%s-%s %s:%s:%s', sscanf($date2, '%4s%2s%2s%2s%2s%2s'));
    
    $diff = abs(strtotime($date2) - strtotime($date1));
    

    or multiple substr string operations + strtotime:

    $date1 = '20120921105240000';
    $date2 = '20120921115626000';
    
    $date1 = substr($date1, 0, 4).'-'.substr($date1, 4, 2).'-'.substr($date1, 6, 2).' '.substr($date1, 8, 2).':'.substr($date1, 10, 2).':'.substr($date1, 12, 2);
    $date2 = substr($date2, 0, 4).'-'.substr($date2, 4, 2).'-'.substr($date2, 6, 2).' '.substr($date2, 8, 2).':'.substr($date2, 10, 2).':'.substr($date2, 12, 2);
    
    $diff = abs(strtotime($date2) - strtotime($date1));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 经gamit解算的cors站数据再经globk网平差得到的坐标做形变分析
  • ¥15 GD32 SPI通信时我从机原样返回收到的数据怎么弄?
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题