首页 文章

PHP中的相对时间与绝对时间

提问于
浏览
0

请检查以下示例:

$date1 = strtotime("tomorrow 4:00 PM");
$date2 = strtotime("16:00:00");
$date3 = strtotime("10 hours");
$date4 = strtotime("+1 day");

echo date("Y m d H:i:s",$date1)."<br>";
echo date("Y m d H:i:s",$date2)."<br>";
echo date("Y m d H:i:s",$date3)."<br>";
echo date("Y m d H:i:s",$date4)."<br>";

它给我输出如下:

2013 06 10 16:00:00
2013 06 09 16:00:00
2013 06 09 20:50:25
2013 06 10 10:50:25

我正在考虑前两个例子($ date1和$ date2)作为绝对数据,最后两个作为相对日期 . 现在,只给出$ date1 / $ date2 / $ date3 / $ date4变量,是否可以说它是相对时间还是绝对时间?

我确实在另一个线程上得到了一个解决方案:PHP datetime string differentiation但是直到我考虑了第二个例子($ date2作为绝对值),它仍然没有't work. Also, may suggested for regular expression checks, but that doesn'似乎可靠 .

我只是想知道php是否有一些集成方式来告诉它的函数或DateTime对象 . 我搜索过,但没有找到任何东西 .

期待收听您的建议/反馈/可能的解决方案 . 谢谢 .

2 回答

  • 2

    只给出值 2013 06 10 16:00:00 答案很简单:它没有's absolute. Whether this absolute timestamp was created as 351614 timestamp or based on relation to another date is impossible to tell. All you have is 351615 , there'或者还有其他类似的东西 .

    即便如此,这与基督所谓的诞生有关,这与大爆炸以来在太空中漂浮的地球有关... * trollface *

  • 0

    没有直接的方法,AFAIK但是有一个技巧可以用于 strtotime 函数的第二个参数 .

    function is_absolute_time($time_string) {
      $time_shift = time() + 60; // 1 min from now
    
      $time_normal = strtotime($time_string);
      $time_shifted = strtotime($time_string, $time_shift);
    
      return $time_normal == $time_shifted;
    }
    

    基本原理很简单:如果时间是绝对的,1分钟的差异不会改变 strtotime 的计算, $time_normal$time_shifted 都是相同的 . 但是,对于相对时间,差异将是一分钟( $time_shift 变量中的值) .

    但是这个代码有一个警告 . 即使是从午夜起不到1分钟的绝对时间(但不是绝对日期),此函数也将返回 FALSE . 您可以通过将 $time_shift 更改为:

    $time_shift = time() + 5; // 5 seconds from now.
    

    此代码现在可以正常工作,直到午夜5秒 . 我认为你可以安全地低至2.有一个边缘情况,未来1秒可能无法正常工作 .

    要完全解决这个问题,您可以尝试不同的方法:

    function is_absolute_time($time_string) {
      $epoch = 0; // Epoch
      $time_shift = 60; // 1 min from epoch
    
      $time_normal = strtotime($time_string, $epoch);
      $time_shifted = strtotime($time_string, $time_shift);
    
      return $time_normal == $time_shifted;
    }
    

    您可以直接尝试最后一个解决方案 . 我只是在这篇文章中 Build 解决方案的原因 .

相关问题