views:

240

answers:

3

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

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

+5  A: 

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);
knittl
I don't have PHP here to test this, but does mktime even accept negative months? It's documented as returning false for invalid arguments.
R. Bemrose
@omg unicorns, yes, from the docs: »mktime() is useful for doing date arithmetic and validation, as it will automatically calculate the correct value for out-of-range input.«
knittl
+2  A: 

A bit hackish but works:

<?php

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

?>
Eric
Oh, hey, I didn't realized DateTime's constructor accepted -6 months. I feel stupid now.
R. Bemrose
+11  A: 

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")));
Adnan
Other than the comma being in the wrong place in the format string, this looks like the best solution (right now, it'd show "October, 1 2009" instead of "October 1, 2009").
R. Bemrose
+1 for being clever :)
Dominic Barnes
right now this shows »Oct, 1 2009«
knittl
hm, ok now? @knittl
Adnan
way better ;) @adnan
knittl
How would you feed in a custom date to this. i.e. instead of using today, choose Feb 2, 2010
stormist
@stormist, then use; date("F, 1 Y", strtotime("-6 months", strtotime("Feb 2, 2010")));
Adnan
@Adnan, don't forget that you could merge those two calls to `strtotime`
salathe
@salathe, excellent point, I can use date("F, 1 Y", strtotime("-6 months Feb 2, 2010")); thank you.
Adnan
this still has the taste of slowness with it. parsing strings for dates and stuff. it works and is short, that's for sure
knittl