23

I need to declare two dates in "Ymd" format: $toDate and $fromDate.

$toDate represents today's date and $fromDate needs to be 4 months earlier than today.

$toDate = Date('Ymd');
$fromDate = ?

How do I create $fromDate?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Jason94
  • 13,320
  • 37
  • 106
  • 184

2 Answers2

59

Use the magic of strtotime:

$fromDate = date("Ymd", strtotime("-4 months"));
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • today at 31st of december i tried the same code and tried to substract 1 month as mentioned above it returned me date of 1st december 2012. however i was expecting 30 november. is it expected result or its a bug? – Mubashar Dec 31 '12 at 05:45
  • @Mubashar I guess it's by design! Both approaches (yours and strtotime's) are arguably equally valid. – Pekka Dec 31 '12 at 11:48
8

see the code below...

$fourmonthsback = date("Ymd", mktime(0, 0, 0, date("m")-4, date("d"),   date("Y")));

OR

$fourmonthsback = mktime(0, 0, 0, date("m")-4, date("d"),   date("Y"));
Prabhu M
  • 2,852
  • 8
  • 37
  • 54
  • 2
    This will not work in january, february, march or april as the month will be either 0 or negative. – cypher Nov 12 '10 at 10:02
  • 8
    @cypher - Actually mktime does date arithmetic. If you set the month parameter to anything less than 1 mktime will choose an earlier month. If you set the month to 0 then mktime will modify the whole date to be December of the previous year. This arithmetic works on all parameters of mktime except for the timezone. – emurano Nov 12 '10 at 10:11
  • Really? Sorry about that then, I didn't know that. – cypher Nov 12 '10 at 11:30