22

Is there a PHP function I can use to do something like the following:

  • Get the date 6 months ago (e.g. now - 6 months)?
  • Get the date 2 years from now (e.g. now + 2 years)?
hakre
  • 193,403
  • 52
  • 435
  • 836
StackOverflowNewbie
  • 39,403
  • 111
  • 277
  • 441

4 Answers4

33

Yes, there is: strtotime():

  1. 6 months ago: strtotime("-6 months");
  2. 2 years: strtotime("+2 years");

These will return Unix timestamps. So you might want to put the result into date() or localtime() or gmtime().

Please do not try to subtract 6 months or add 2 years of seconds to time(). This does not take into account things like daylight saving or leap seconds and still gives you a value in seconds which is unlikely to be the precision you need. Let the library functions do it.

Mofi
  • 46,139
  • 17
  • 80
  • 143
staticsan
  • 29,935
  • 4
  • 60
  • 73
12

Like this:

$date6monthsago = strtotime('-6 months');
$date2year = strtotime('+2 year');
Book Of Zeus
  • 49,509
  • 18
  • 174
  • 171
6

Choose according to your use following code..

echo date('m/d/Y',strtotime("-6 months")); //ago 6month o/p 05/23/2011 
echo date('d-m-Y',strtotime("6 months"));  //comming 6month o/p 23-05-2012
echo date('m.d.Y',strtotime("+2 years"));  //comming year o/p 11.23.2013
0

http://de2.php.net/manual/en/datetime.add.php and similar "new" methods may also be your friend.

patriziotomato
  • 591
  • 1
  • 11
  • 25