【问题标题】:UTC time with 7 decimals calculation7 位小数计算的 UTC 时间
【发布时间】:2020-05-21 12:09:38
【问题描述】:

我需要在 PHP 7.3 中计算 2 个带 7 位小数的 UTC 时间值之间的差异

我可以简单地执行以下操作吗:

val1 = 20200205120415.6513380; //first timestamp
val2 = 20200205120415.6535670; //second timestamp
$diff = $val2 - $val1; //should be difference between the 2 timestamps

上述计算的值为0.002229。如果我做得正确,该值以秒或微秒为单位,我能否将其转换为 UNIX 纪元时间戳?

【问题讨论】:

    标签: php unix utc epoch seconds


    【解决方案1】:

    我强烈怀疑上述时间不是简单的数字;它们是 2020-02-05-12:04:15.6513380 的 BCD(二进制编码的十进制)。您无法对这些进行简单的数学运算,您需要解析它们以转换为 unix 时间戳。

    根据您的语言,最简单的方法可能是将它们转换为字符串并将前四个字符作为年份,接下来的两个字符作为月份,等等。

    【讨论】:

      【解决方案2】:

      这是我目前的完整性解决方案。

      右侧的值。确实是小数秒。因此,在 PHP 中,为了获得差异,我做了以下操作:

      $start = 20200205120415.6513380;
      $end = 20200205120415.6535670;
      
      //get value left of . and then create datetime object to later convert to seconds
      list($datetime, $usecStart) = explode(".", $start);
      $startTime = date_create_from_format("YmdHis", $datetime);
      list($datetime, $usecEnd) = explode(".", $end);
      $endTime = date_create_from_format("YmdHis", $datetime);
      
      //get timestamp in seconds and add franction or microseconds back
      $start = $startTime->getTimestamp().".".$usecStart;
      $end = $endTime->getTimestamp().".".$usecEnd;
      
      //get difference in seconds and fraction or microseconds
      echo $end - $start;
      

      这里是另一种使用 datetime->diff() 函数的方法:

      $start = new DateTime('2020-02-05T12:04:15.6513380Z');
      $end = new DateTime('2020-02-05T12:04:15.6535670Z');
      
      $diff = $start->diff($end);
      echo $diff->format('%h:%i:%s.%F');
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-04-13
        • 1970-01-01
        • 1970-01-01
        • 2023-01-11
        • 1970-01-01
        • 2021-11-14
        • 2015-09-25
        相关资源
        最近更新 更多