简体   繁体   中英

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

So if today was April 12, 2010 it should return October 1, 2009

Some possible solutions I've googled seem overly complex, any suggestions?

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

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

A bit hackish but works:

<?php

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

?>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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