如何获得给定月份的第一天和最后一天

dol*_*oug 63 php date

我希望重写一个mysql查询,它使用month()和year()函数显示某个月的所有帖子,这些帖子作为'Ymd'参数格式转到我的函数,但我不知道如何才能获得给定月份日期的最后一天.

$query_date = '2010-02-04';
list($y, $m, $d) = explode('-', $query_date);
$first_day = $y . '-' . $m . '-01';
Run Code Online (Sandbox Code Playgroud)

Fra*_*nes 135

您可能想要查看strtotimedate函数.

<?php

$query_date = '2010-02-04';

// First day of the month.
echo date('Y-m-01', strtotime($query_date));

// Last day of the month.
echo date('Y-m-t', strtotime($query_date));
Run Code Online (Sandbox Code Playgroud)


Gol*_*bug 16

我知道这个问题与't'有一个很好的答案,但我想我会添加另一个解决方案.

$first = date("Y-m-d", strtotime("first day of this month"));
$last = date("Y-m-d", strtotime("last day of this month"));
Run Code Online (Sandbox Code Playgroud)

  • 这个解决方案是错误的,因为问题是关于“给定月份”,但您的答案仅适用于当月。 (2认同)

Moh*_*eer 12

如果您在PHP中使用PHP 5.3+,请尝试此操作

$query_date = '2010-02-04';
$date = new DateTime($query_date);
//First day of month
$date->modify('first day of this month');
$firstday= $date->format('Y-m-d');
//Last day of month
$date->modify('last day of this month');
$lastday= $date->format('Y-m-d');
Run Code Online (Sandbox Code Playgroud)

要查找下个月的最后日期,请修改如下,

 $date->modify('last day of 1 month');
 echo $date->format('Y-m-d');
Run Code Online (Sandbox Code Playgroud)

等等..


Jon*_*nix 7

cal_days_in_month()应该为您提供该月的总天数,因此也就是最后一天.