繁体   English   中英

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

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

我想重写一个 mysql 查询,它使用 month() 和 year() 函数来显示某个月份的所有帖子,这些帖子以“Ymd”参数格式发送到我的 function,但我不知道如何获得给定月份日期的最后一天。

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

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

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

如果您在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');

等等..

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

日期 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("Ym-01", strtotime("January")); echo $last = date("Ymt", strtotime("January"));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM