如何获取给定月份的第一天和最后一天
问题描述:
我希望重写一个使用month()和year()函数的mysql查询来显示某个月的所有帖子,这些帖子会作为'Ymd '参数格式,但我不知道如何才能得到给定月份日期的最后一天。如何获取给定月份的第一天和最后一天
$query_date = '2010-02-04';
list($y, $m, $d) = explode('-', $query_date);
$first_day = $y . '-' . $m . '-01';
答
基本上是:
$lastDate = date("Y-m-t", strtotime($query_d));
日期吨参数回天数在当月。
答
cal_days_in_month()应该给你一个月的总天数,因此,最后一天。
+0
感谢您的分享。我从来没有使用过日历PHP模块。有鉴于此,值得指出的是,模块*可能不会被安装,尤其是在共享主机上。 –
答
我知道这个问题用't'有个很好的答案,但我认为我会添加另一个解决方案。
$first = date("Y-m-d", strtotime("first day of this month"));
$last = date("Y-m-d", strtotime("last day of this month"));
答
试试这个,如果你使用的是PHP 5.3+,在PHP
$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');
为了找到下个月最后日期,修改如下,
$date->modify('last day of 1 month');
echo $date->format('Y-m-d');
等..
答
// First date of the current date
echo date('Y-m-d', mktime(0, 0, 0, date('m'), 1, date('Y')));
echo '<br />';
// Last date of the current date
echo date('Y-m-d', mktime(0, 0, 0, date('m')+1, 0, date('Y')));
答
$month = 10; // october
$firstday = date('01-' . $month . '-Y');
$lastday = date(date('t', strtotime($firstday)) .'-' . $month . '-Y');
ty:你的方法更聪明。不需要爆炸。 –
如果$ query_date来自php的'd-m-Y'格式:'02-04-2010'怎么办?在我的测试中,它很好,但也许我没有测试所有的情况。我是否必须转换为Y-m-d或时间,无论如何都要理解它。 –
支持“d-m-Y”格式。支持的格式列于[http://ca2.php.net/manual/en/datetime.formats.date.php](http://ca2.php.net/manual/en/datetime.formats.date。 PHP)。 –