【问题标题】:Getting the first day of the month of a specific month/year获取特定月/年的第一天
【发布时间】:2012-03-02 15:40:12
【问题描述】:

有没有比以下方法更好的方法来返回特定月/年第一天的日期?

$month = date('m');
$year = date('Y');
$from = date('Y-m-d', mktime(0, 0, 0, $month, 1, $year));

【问题讨论】:

  • 更好是什么意思?你所拥有的似乎很好。

标签: php date


【解决方案1】:

这在计算上并不完全优雅,但我喜欢它,因为它可读性强:

strtotime("first day of this month");

【讨论】:

  • 值得注意的是,“下个月的第一天”和“本月的第一天 + 2 个月”等变体也有效。
  • 另外值得注意的是,与问题中以午夜为时间的示例不同,此版本使用当前的小时、分钟和秒。
  • 我喜欢用$date = new DateTime('first day of this month'); $date->setTime(0, 0, 0);
【解决方案2】:

为什么这么复杂?

date("Y-m-01")

这会很好用;)

(别担心,在意识到我可以做到这一点之前,我浪费了一个小时与strtotime 纠缠不清!)

【讨论】:

    【解决方案3】:

    date("Y-m-01") 将完美运行; 我使用相同的技术来查找从当月第一天到当天的记录。 查看以下代码行:

    if(!isset($FromDate))
              $FromDate=date('Y-m-01'); //date with current month's first day
    
    if(!isset($ToDate))
             $ToDate=date('Y-m-d'); /////current date
    

    我希望它能按要求工作。

    【讨论】:

      【解决方案4】:

      这对我来说似乎是正确的做法。不过你可能想把它变成一个函数。

      【讨论】:

        猜你喜欢
        • 2019-03-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-29
        相关资源
        最近更新 更多