【问题标题】:How do I find the unix timestamp for the start of the next day in php?如何在php中找到第二天开始的unix时间戳?
【发布时间】:2013-12-10 18:55:24
【问题描述】:

我有一个当前时间的 unix 时间戳。我想获取第二天开始的 unix 时间戳。

$current_timestamp = time();
$allowable_start_date = strtotime('+1 day', $current_timestamp);

正如我现在所做的那样,我只是将一整天的时间添加到 unix 时间戳,而我想弄清楚这一天还剩下多少秒,并且只添加那几秒以便获取第二天第一分钟的 unix 时间戳。

最好的方法是什么?

【问题讨论】:

    标签: php unix-timestamp


    【解决方案1】:

    当时最直接的“make”方式:

    $tomorrowMidnight = mktime(0, 0, 0, date('n'), date('j') + 1);
    

    引用:

    我想知道这一天还剩下多少秒,并且只添加那几秒以获得第二天第一分钟的 unix 时间戳。

    不要那样做。尽可能避免相对计算,特别是如果“绝对”在没有秒算术的情况下获取时间戳是如此微不足道。

    【讨论】:

    • 那么这个和strtotime('+1 day', mktime(0, 0, 0))一样吗?
    • @zeckdude 基本上是的,我会说效率更高,因为strtotime 功能强大,但速度较慢。此外,您明确地制作了一个时间戳在午夜,而不是在午夜的时间戳中添加一天,这在夏令时切换等边缘情况下可能更可靠,也可能不更可靠。
    【解决方案2】:

    您可以通过以下方式轻松获得明天午夜时间戳:

    $tomorrow_timestamp = strtotime('tomorrow');
    

    如果您希望能够执行可变天数,您可以轻松地这样做:

    $days = 4;
    $x_num_days_timestamp = strtotime(date('m/d/Y', strtotime("+$days days"))));
    

    【讨论】:

    • 正如 deceze 在上面指出的 strtotime('+1 day', mktime(0, 0, 0)) 比我给出的嵌套解决方案更优雅。所以:$days = 4; $x_num_days_timestamp = strtotime("+$days days", mktime(0, 0, 0));
    【解决方案3】:
    $tomorrow = strtotime('+1 day', strtotime(date('Y-m-d')));
    $secondsLeftToday = time() - $tomorrow;
    

    【讨论】:

    • $tomorrow 行是一种非常复杂的方式来处理strtotime('+1 day', mktime(0, 0, 0))
    • 酷,这绝对是最清晰的。
    【解决方案4】:

    简单的:

    $nextday = $current_timestamp + 86400 - ($current_timestamp % 86400);
    

    是我会使用的。

    【讨论】:

    • 什么是 86400?这个数字代表什么?
    • 因此,如果我想使用相同的想法,但要获取从现在开始两天后的时间戳,我只需将该数字加倍,例如 $twodays = $current_timestamp + 172800 - ( $current_timestamp % 172800); ?
    • 86400 是一天中的秒数
    • 这是错误的,因为一天并不总是有 24 小时。见daylight saving time
    【解决方案5】:

    第二天的开始计算如下:

    <?php
    
    $current_timestamp = time();
    $allowable_start_date = strtotime('tomorrow', $current_timestamp);
    
    echo date('r', $allowable_start_date);
    
    ?>
    

    如果它需要遵循您的特殊要求:

    <?php
    
    $current_timestamp = time();
    $seconds_to_add = strtotime('tomorrow', $current_timestamp) - $current_timestamp;
    
    echo date('r', $current_timestamp + $seconds_to_add);
    
    ?>
    

    【讨论】:

      【解决方案6】:

      我的变种:

       $allowable_start_date = strtotime('today +1 day');
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-12-15
        • 2011-11-03
        • 1970-01-01
        • 2018-01-21
        • 2011-05-04
        • 1970-01-01
        • 2016-07-30
        • 1970-01-01
        相关资源
        最近更新 更多