【发布时间】:2011-11-23 00:35:37
【问题描述】:
是否有一个 PHP 函数可以用来执行以下操作:
- 获取 6 个月前的日期(例如现在 - 6 个月)?
- 获取从现在起 2 年后的日期(例如现在 + 2 年)?
【问题讨论】:
-
我认为 PHP 的
strtotime()相当普遍。
标签: php
是否有一个 PHP 函数可以用来执行以下操作:
【问题讨论】:
strtotime() 相当普遍。
标签: php
是的,有:strtotime():
strtotime("-6 months");
strtotime("+2 years");
这些将返回 Unix 时间戳。因此,您可能希望将结果放入 date() 或 localtime() 或 gmtime()。
请不要尝试在time() 中减去 6 个月或增加 2 年的秒数。这没有考虑夏令时或闰秒等因素,并且仍然为您提供以秒为单位的值,这不太可能是您需要的精度。让库函数来做吧。
【讨论】:
strtotime 正是我所需要的。
date('Y-m-d', strtotime('-1 month', strtotime('2013-03-31'))) 给出2013-03-03。
像这样:
$date6monthsago = strtotime('-6 months');
$date2year = strtotime('+2 year');
【讨论】:
根据你的使用选择下面的代码..
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
【讨论】:
http://de2.php.net/manual/en/datetime.add.php 和类似的“新”方法也可能是您的朋友。
【讨论】: