如何得到一个月的第一天和最后一天


how to get the first and last days of a given month

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

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

您可能想看看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));

我知道这个问题有一个很好的答案,但我想我应该添加另一个解决方案。

$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');

cal_days_in_month()应该给出一个月中的总天数,因此是最后一个。

// 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');

基本上:

$lastDate = date("Y-m-t", strtotime($query_d));

Date t参数返回当前月份的天数。

只打印当前月份和星期:

function my_week_range($date) {
    $ts = strtotime($date);
    $start = (date('w', $ts) == 0) ? $ts : strtotime('last sunday', $ts);
    echo $currentWeek = ceil((date("d",strtotime($date)) - date("w",strtotime($date)) - 1) / 7) + 1;
    $start_date = date('Y-m-d', $start);$end_date=date('Y-m-d', strtotime('next saturday', $start));
    if($currentWeek==1)
        {$start_date = date('Y-m-01', strtotime($date));}
    else if($currentWeek==5)
       {$end_date = date('Y-m-t', strtotime($date));}
    else
       {}
    return array($start_date, $end_date );
}
$date_range=list($start_date, $end_date) = my_week_range($new_fdate);
## Get Current Month's First Date And Last Date
echo "Today Date: ". $query_date = date('d-m-Y');
echo "<br> First day of the month: ". date('01-m-Y', strtotime($query_date));
echo "<br> Last day of the month: ". date('t-m-Y', strtotime($query_date));

对于月份的名称,此代码将工作

echo $first = date("Y-m-01", strtotime("January"));
echo $last = date("Y-m-t", strtotime("January"));