【问题标题】:How to calculate a relative date based on a date string如何根据日期字符串计算相对日期
【发布时间】:2023-03-08 05:08:01
【问题描述】:

我想在用户提供的日期之后找到日期

这不起作用:

$start_date = '2009-06-10';

$next_day = date( $start_date, strtotime('+1 day') );     

echo $next_day; // 2009-06-10

【问题讨论】:

    标签: php date


    【解决方案1】:

    尝试 date_modify:

    $d = new DateTime("2009-01-01"); 
    date_modify($d, "+1 day"); 
    echo $d->format("Y-m-d");
    

    http://us3.php.net/manual/en/datetime.modify.php 的文档。

    【讨论】:

    • 为什么不直接使用 DateTime 中的“修改”方法呢?
    • DateTime::modify 是 date_modify 的别名。
    【解决方案2】:
    $start_date = '2009-06-10';
    
    $next_day = date( 'Y-m-d', strtotime( '+1 day', strtotime($start_date) ) );
    
    echo $next_day; // 2009-06-11
    

    【讨论】:

    • 第二行可以是:$next_day = date('Y-m-d', strtotime($start_date.' +1 day'));
    【解决方案3】:
    $start_date = '2009-06-10';
    $next_day = new DateTime($start_date)->modify("+1 day")->format("Y-m-d"); 
    

    编辑:

    正如 Kristina 指出的那样,此方法不起作用,因为 DateTime::modify 不会像我怀疑的那样返回修改后的日期。 (PHP,我讨厌你的不一致!)

    此代码现在按预期工作,恕我直言,看起来比 date_modify 更一致 :)

    $start_date = '2009-06-10';
    
    $next_day = new DateTime($start_date);
    $next_day->modify("+1 day")
    
    echo $next_day->format("Y-m-d"); 
    

    【讨论】:

    • DateTime::modify() 返回 NULL,而不是 DateTime 对象(文档错误),所以这不起作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 2011-06-04
    • 2014-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多