【问题标题】:Date Arithmetic in PHPPHP中的日期算术
【发布时间】:2011-11-23 00:35:37
【问题描述】:

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

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

【问题讨论】:

  • 我认为 PHP 的 strtotime() 相当普遍。

标签: php


【解决方案1】:

是的,有:strtotime():

  1. 6 个月前:strtotime("-6 months");
  2. 2年: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
  • @Tammlyn 这是一个有趣的错误!我相当确定 strtotime 调用了底层 glibc 调用。
  • 哦 - 我知道为什么会这样:它使 3 月 31 日到 2 月 31 日不存在,然后将其转换为 3 月 3 日。这是一个很难解决的错误!
【解决方案2】:

像这样:

$date6monthsago = strtotime('-6 months');
$date2year = strtotime('+2 year');

【讨论】:

    【解决方案3】:

    根据你的使用选择下面的代码..

    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
    

    【讨论】:

      【解决方案4】:

      http://de2.php.net/manual/en/datetime.add.php 和类似的“新”方法也可能是您的朋友。

      【讨论】:

        猜你喜欢
        • 2011-10-05
        • 1970-01-01
        • 2017-08-23
        • 2011-02-23
        • 1970-01-01
        • 2021-02-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多