PHP:获取第一个月份前 6 个月日期的最简单方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2625469/
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: simplest way to get the date of the month 6 months prior on the first?
提问by stormist
So if today was April 12, 2010 it should return October 1, 2009
所以如果今天是 2010 年 4 月 12 日,它应该返回 2009 年 10 月 1 日
Some possible solutions I've googled seem overly complex, any suggestions?
我用谷歌搜索的一些可能的解决方案似乎过于复杂,有什么建议吗?
回答by Adnan
Hm, maybe something like this;
嗯,也许是这样的;
echo date("F 1, Y", strtotime("-6 months"));
EDIT;
编辑;
if you would like to specify a custom date use;
如果您想指定自定义日期使用;
echo date("F, 1 Y", strtotime("-6 months", strtotime("Feb 2, 2010")));
回答by knittl
use a combination of mktimeand date:
$date_half_a_year_ago = mktime(0, 0, 0, date('n')-6, 1, date('y'))
to make the new date relative to a given date and not today, call datewith a second parameter
要使新日期相对于给定日期而不是今天,请date使用第二个参数调用
$given_timestamp = getSomeDate();
$date_half_a_year_ago = mktime(0, 0, 0, date('n', $given_timestamp)-6, 1, date('y', $given_timestamp))
to output it formatted, simply use dateagain:
要输出格式化,只需date再次使用:
echo date('F j, Y', $date_half_a_year_ago);
回答by Eric G
A bit hackish but works:
有点hackish但有效:
<?php
$date = new DateTime("-6 months");
$date->modify("-" . ($date->format('j')-1) . " days");
echo $date->format('j, F Y');
?>
回答by billynoah
It was discussed in comments but the accepted answer has some unneeded strtotime()calls. Can be simplified to:
它在评论中进行了讨论,但接受的答案有一些不需要的strtotime()电话。可以简化为:
date("F 1, Y", strtotime("Feb 2, 2010 - 6 months"));
Also, you can use DateTime()like this which I think is equally as readable:
此外,您可以DateTime()像这样使用我认为同样可读的:
(new DateTime('Feb 2, 2010'))->modify('-6 months')->format('M 1, Y');
Or using static method....
或者使用静态方法....
DateTime::createFromFormat('M j, Y','Feb 2, 2010')
->modify('-6 months')
->format('M 1, Y');

