php php获取给定月份的最后一天
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33139436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
php get last day of given month
提问by Frai1989
I want to output of last and first date of a given month of current year. I am using this code but not works
我想输出当年给定月份的最后一个和第一个日期。我正在使用此代码但不起作用
$month='02';
$first_day_this_month = date('Y-'.$month.'-01'); // hard-coded '01' for first day
$last_day_this_month = date('Y-'.$month.'-t');
echo $first_day_this_month;print'<->';echo $last_day_this_month;
my output shows
我的输出显示
2015-02-01<->2015-02-31
But it will be 2015-02-01<->2015-02-28
但它会 2015-02-01<->2015-02-28
回答by Ushal Naidoo
I have had this problem with PHP before, try the following way:
我以前用PHP遇到过这个问题,请尝试以下方法:
$dateToTest = "2015-02-01";
$lastday = date('t',strtotime($dateToTest));
回答by Agustin Silva Albistur
there are many ways to do that, i give you two answers\ideas:
有很多方法可以做到这一点,我给你两个答案\想法:
1- Try to use strtotime
PHP function (http://php.net/manual/es/function.strtotime.php)
1- 尝试使用strtotime
PHP 函数(http://php.net/manual/es/function.strtotime.php)
Something like date("Y-m-d", strtotime("last day of this month"));
or first day... or any month.
像date("Y-m-d", strtotime("last day of this month"));
或第一天……或任何一个月。
2- Other way you can use that:
2-您可以使用的其他方式:
First day:
第一天:
date("Y-m-d", mktime(0, 0, 0, *YOUR MONTH PARAM*,1 ,date("Y")));
Last day:
最后一天:
date("Y-m-d", mktime(0, 0, 0, *YOUR MONTH PARAM*+1,0,date("Y")));
Read about mktimefunction here:
在此处阅读有关mktime功能的信息:
http://php.net/manual/es/function.mktime.php
http://php.net/manual/es/function.mktime.php
Good luck!
祝你好运!
回答by Gautier
You can use DateTime methods:
您可以使用 DateTime 方法:
$month = '02';
$date = new DateTime(date('Y').'-'.$month.'-01');
$date->modify('first day of this month');
$first_day_this_month = $date->format('Y-m-d');
$date->modify('last day of this month');
$last_day_this_month = $date->format('Y-m-d');
回答by ercvs
You can with DateTime class.
您可以使用 DateTime 类。
$month='02';
$first_day_this_month = date('Y-'.$month.'-01');
$firstDayThisMonth = new \DateTime($first_day_this_month);
$lastDayThisMonth = new \DateTime($firstDayThisMonth->format('Y-m-t'));
$lastDayThisMonth->setTime(23, 59, 59);
echo $firstDayThisMonth->format("Y-m-d");
echo "<->";
echo $lastDayThisMonth->format("Y-m-d");