PHP: simplest way to get the date of the month 6 months prior on the first?

ぐ巨炮叔叔 提交于 2019-11-30 10:50:43

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

A bit hackish but works:

<?php

$date = new DateTime("-6 months");
$date->modify("-" . ($date->format('j')-1) . " days");
echo $date->format('j, F Y');

?>

use a combination of mktime and 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 date with a second parameter

$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 date again:

echo date('F j, Y', $date_half_a_year_ago);

It was discussed in comments but the accepted answer has some unneeded strtotime() calls. Can be simplified to:

date("F 1, Y", strtotime("Feb 2, 2010 - 6 months"));

Also, you can use DateTime() like this which I think is equally as readable:

(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');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!