PHP中的日期算术

Sta*_*bie 22 php

是否有一个PHP函数,我可以用来执行以下操作:

  • 获取6个月前的日期(例如现在 - 6个月)?
  • 获取2年后的日期(例如现在+ 2年)?

sta*_*san 33

是的,有:strtotime():

  1. 6个月前: strtotime("-6 months");
  2. 2年: strtotime("+2 years");

这些将返回Unix时间戳.所以你可能想把结果放入date()localtime()gmtime().

请不要试图减去6个月或增加2年的秒数time().这不会考虑夏令时或闰秒之类的事情,但仍然会以秒为单位给出一个不太可能达到所需精度的值.让库函数做到这一点.

  • 哦 - 我知道它为什么这样做:它在3月31日到2月31日不存在,所以然后将它转换为3月3日.这是一个棘手的错误要解决! (4认同)
  • 日期算术有点可疑.例如`date('Ym-d',strtotime(' - 1 month',strtotime('2013-03-31')))`给出`2013-03-03`. (2认同)

Boo*_*eus 12

像这样:

$date6monthsago = strtotime('-6 months');
$date2year = strtotime('+2 year');
Run Code Online (Sandbox Code Playgroud)


小智 6

根据您的使用选择以下代码..

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
Run Code Online (Sandbox Code Playgroud)