【问题标题】:How to get timestamp of current month, first day of month, zero hour如何获取当月的时间戳,当月的第一天,零小时
【发布时间】:2012-06-29 12:06:59
【问题描述】:

我正在尝试获取该月第一天 00:00:00 的时间戳。

例如 2012 年 1 月 1 日 00:00:00 的时间戳

我正在这样做:

$test_month = time(); // Seconds
$test_month = date('M', $test_month); // This month
$test_month = strtotime($test_month); // Timestamp of this month
echo $test_month;

这是返回当月当天的零时,而不是月初。

有什么建议吗?

【问题讨论】:

    标签: php date timestamp strtotime


    【解决方案1】:

    试试这个

    $time = strtotime(date('Y-m-01 00:00:00')); // == 1338534000
    

    翻译为:

    $date = date('Y-m-d H:i:s', $time); // == 2012-06-01 00:00:00
    

    阅读有关date()time() 函数的PHP 手册。

    【讨论】:

    【解决方案2】:

    试试这个:

    echo date( 'F jS Y h:i:s A', strtotime( 'first day of ' . date( 'F Y')));
    

    这将输出:

    June 1st 2012 12:00:00 AM
    

    【讨论】:

    • 哇,我什至不知道“第一天”的存在。伟大的!谢谢。
    • @JohnRobinson - 不客气!它实际上记录在list of supported relative times 上。如果我的帖子回答了您的问题,请考虑接受。
    • 你不需要使用date('F Y'),你可以使用strtotime('first day of this month')。您甚至可以添加另一个时间的时间戳作为第二个参数来获取该月的第一天。
    • strtotime("first day of this month midnight")。添加 午夜 将导致 12:00 AM。
    • 对我来说似乎不是一个容易记住的解决方案,因为使用了 F、jS 占位符。更喜欢其他答案中的数据库格式。而简单地使用strtotime('first of this month')(不带日期参数)似乎也是一个很好的、可能容易记住的解决方案。
    【解决方案3】:
    echo date("Y-m-d 00:00:00", strtotime("first day of this month"));
    

    这个输出:

    2017-05-01 00:00:00
    

    【讨论】:

    • 这个答案看起来也比 stackoverflow.com/a/11236766/669210 中的解决方案更干净,因为我认为该格式使用频率更高。
    猜你喜欢
    • 2021-06-11
    • 1970-01-01
    • 2013-10-29
    • 2019-09-10
    • 1970-01-01
    • 2011-02-25
    • 2014-03-22
    • 2017-02-07
    • 1970-01-01
    相关资源
    最近更新 更多