【问题标题】:Adding X weeks to a date using PHP 5.2使用 PHP 5.2 将 X 周添加到日期
【发布时间】:2012-04-13 05:02:27
【问题描述】:

我在 1and1 的共享主机包只包含 PHP 5.2.17——所以我不能使用 DateTime 对象。很烦人!

我目前有这个代码

$eventDate = new DateTime('2013-03-16'); // START DATE
$finishDate = $eventDate->add(new DateInterval('P'.$profile["Weeks"].'W'));

但显然它不会起作用。

我怎样才能对适用于 PHP5.2 的代码做同样的事情? (代码将 X 周数添加到特定日期。)

【问题讨论】:

    标签: php datetime php-5.2


    【解决方案1】:

    只需使用 strtotime() 获取时间戳并添加一周的 x * 秒

    $newTime = strtotime('2013-03-16') + ($numberOfWeeks * 60 * 60 * 24 * 7); // 604800 seconds
    

    或者我刚刚发现的:

    $newTime = strtotime('+'.$numberOfWeeks.' weeks', strtotime('2013-03-16'));
    

    您也可以使用DateTime 类。使用方法modify 更改您的日期(如strtotime):

    $d = new DateTime('2013-03-16');
    $d->modify('+'.$numberOfWeeks.' weeks');
    

    【讨论】:

    • strtotime() 带来的问题比看起来要多。使用DateTime类函数,避免计算周期时出现奇怪的错误,你不会错过一秒钟。
    • @Paul 您知道这与 PHP 5.2 中缺少的 DateInterval 有关吗?当然,总会有其他答案。
    • 那么来自 PHP 5.2.0DateTime::modify() 呢?它也适用于正值和负值。就在几天前,我已经更正了我自己的产品 bec 中的错误。我正在通过时间戳的差异计算间隔,并且在 2 个月(10 月至 11 月)的边缘上失去了 2 周。更正为DateTime 实现,就是这样。
    • @Paul 我知道整套DateTime,谢谢。我只是在那个特定时间没有想到这个。我的其他答案总是表明更喜欢DateTimeDateIntervalDatePeriod 的集合。这是一个特例。而且当您拥有 PHP 5.2 时,strtotime 是您遇到的最少问题!
    • 嘿,:) 用DateTime 更新你的答案,我记得会投票!剩下 10 分让你获得几乎一轮的代表:)
    【解决方案2】:

    您可以在 PHP 5.2 中使用 DateTime 对象,它只是 PHP 5.3 中添加的 add 方法。你可以在 PHP 5.2 中使用the modify method

    $finishDate = $eventDate->modify('+'.$profile["Weeks"].' weeks');
    

    请注意,这将修改您对其执行操作的对象。所以 $eventDate 也会被改变。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 2013-11-18
      • 1970-01-01
      • 2011-07-08
      • 1970-01-01
      相关资源
      最近更新 更多