PHP 中的日期算术
2022-08-30 18:57:43
有没有一个PHP函数,我可以用来做类似的事情:
- 获取 6 个月前的日期(例如现在 - 6 个月)?
- 从现在起 2 年后获取日期(例如,现在 + 2 年)?
有没有一个PHP函数,我可以用来做类似的事情:
是的,有:strtotime():
strtotime("-6 months");
strtotime("+2 years");
这些将返回 Unix 时间戳。因此,您可能希望将结果放入 或 或 中。date()
localtime()
gmtime()
请不要尝试减去 6 个月或将 2 年的秒数添加到 。这没有考虑夏令时或闰秒之类的东西,仍然为您提供以秒为单位的值,这不太可能是您需要的精度。让库函数来做吧。time()
喜欢这个:
$date6monthsago = strtotime('-6 months');
$date2year = strtotime('+2 year');