【问题标题】:Fetch timestamp of the midnight before a given timestamp获取给定时间戳之前午夜的时间戳
【发布时间】:2011-11-03 11:23:13
【问题描述】:

给定任何 unix-timestamp T,我想获取 T 之前午夜的时间戳。

给定的时间戳可以是任何整数:现在、今天、未来(不太远[])或过去(不太远[])。

那么有没有更干净的方法(伪代码):

<?php
$midnight = strtotime("{date('d',$ts)}-{date('m',$ts)}-{date('Y', $ts)} midnight");
?>

谢谢。

[*] 介于 1990 年和 2020 年之间。

【问题讨论】:

    标签: php timestamp


    【解决方案1】:

    我会这样做

    $midnight = strtotime(date('Y-m-d',$ts).' 00:00:00');
    

    ...但是这是否更清洁/更好还有待商榷...

    【讨论】:

    • 谢谢。我担心通过 strtotime 的路线是唯一的“务实”方法。你的是最干净的。
    【解决方案2】:

    由于一整天是 86400 秒,您应该可以这样做:

    $midnight = $ts - $ts%86400;
    

    但是,这不会考虑可能已应用于 unix 时间戳的任何闰秒。

    这比使用 strtotime 性能要好得多,但可能只有在大而紧凑的循环中这样做才有意义。

    【讨论】:

      【解决方案3】:

      瞧瞧'

      <?php    
      $midnight = strtotime(date('d-m-Y',$ts));
      echo date('d-m-Y H:i:s',$ts);       // output 03-11-2011 12:43:41
      echo date('d-m-Y H:i:s',$midnight); // ouput 03-11-2011 00:00:00
      ?>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-10-19
        • 1970-01-01
        • 2012-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多