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

时间:2011-09-24 21:08:11

标签: php date

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

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

9 个答案:

答案 0 :(得分:122)

您可能需要查看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));

答案 1 :(得分:10)

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

$first = date("Y-m-d", strtotime("first day of this month"));
$last = date("Y-m-d", strtotime("last day of this month"));

答案 2 :(得分:9)

试试这个,如果你在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');

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

 $date->modify('last day of 1 month');
 echo $date->format('Y-m-d');

依旧......

答案 3 :(得分:6)

cal_days_in_month()应该会显示当月的总天数,因此也就是最后一天的天数。

答案 4 :(得分:1)

基本上:

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

日期 t参数当月的返回天数。

答案 5 :(得分:1)

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

答案 6 :(得分:1)

$month = 10; // october

$firstday = date('01-' . $month . '-Y');
$lastday = date(date('t', strtotime($firstday)) .'-' . $month . '-Y');

答案 7 :(得分:0)

仅打印当前月份的周:

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

答案 8 :(得分:0)

## 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));
相关问题