php 获取当前年份的最后一天作为日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21976813/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:35:58  来源:igfitidea点击:

Get the last day of the current year as date

phpdatetimedatetime-formatdate-arithmetic

提问by user2571510

How can I get the last day (Dec 31) of the current year as a date using PHP?

如何使用 PHP 获取当前年份的最后一天(12 月 31 日)作为日期?

I tried the following but this doesn't work:

我尝试了以下操作,但这不起作用:

$year = date('Y');
$yearEnd =  strtotime($year . '-12-31');

What I need is a date that looks like 2014-12-31 for the current year.

我需要的是今年看起来像 2014-12-31 的日期。

回答by AbraCadaver

PHP strtotime()uses the current date/time as a basis (so it will use this current year), and you need date()to format:

PHPstrtotime()使用当前日期/时间作为基础(因此它将使用当前年份),并且您需要date()格式化:

$yearEnd = date('Y-m-d', strtotime('Dec 31'));

//or

$yearEnd = date('Y-m-d', strtotime('12/31'));

回答by Fabio

You can just concatenate actual year with required date

您可以将实际年份与所需日期连接起来

$year = date('Y') . '-12-31';
echo $year;
//output 2014-12-31

回答by xtra

DateTime is perfectly capable of doing this:

DateTime 完全有能力做到这一点:

$endOfYear = new \DateTime('last day of December this year');

You can even combine it with more modifiers to get the end of next year:

您甚至可以将其与更多修改器结合使用,以获得明年年底:

$endOfNextYear = new \DateTime('last day of December this year +1 years');

回答by Maurice

Another way to do this is use the Relative Formats of strtotime()

另一种方法是使用相对格式 strtotime()

$yearEnd = date('Y-m-d', strtotime('last day of december this year'));

// or

$yearEnd = date('Y-m-d', strtotime('last day of december'));