php string in a date format, add 12 hours

前端 未结 4 1432
无人共我
无人共我 2020-12-19 09:26

I have this string object in my php array

\"2013-03-05 00:00:00+00\"

I would like to add 12 hours to the entry within PHP, then save it back to

相关标签:
4条回答
  • 2020-12-19 09:40

    Change add() to modify(). add() expects a DateInterval object.

    <?php
    $date = new DateTime("2013-03-05 00:00:00+00");
    $date->modify("+12 hours");
    echo $date->format("Y-m-d H:i:sO");
    

    See it in action

    Here's an example using a DateInterval object:

    <?php
    $date = new DateTime("2013-03-05 00:00:00+00");
    $date->add(new DateInterval('PT12H'));
    echo $date->format("Y-m-d H:i:sO");
    

    See it in action

    0 讨论(0)
  • 2020-12-19 09:46

    Use this to add hours,

    $date1= "2014-07-03 11:00:00";
    $new_date= date("Y-m-d H:i:s", strtotime($date1 . " +3 hours"));
    echo $new_date;
    
    0 讨论(0)
  • 2020-12-19 09:48

    If you have dynamic interval, this way will avoid errors of wrong format for $dateDiff:

    $dateDiff = "12 hours";
    $interval = DateInterval::createFromDateString($dateDiff);
    $date = new DateTime("2013-03-05 00:00:00+00");
    $date->add($interval);
    echo $date->format("Y-m-d H:i:sO");
    
    0 讨论(0)
  • 2020-12-19 09:49

    Change this line

    $date->add("+12 hours");
    

    with

    $date->add(new DateInterval("PT12H"));
    

    this will add 12 hours to your date

    Look at the DateInterval constructor page to know how to build the DateInterval string

    0 讨论(0)
提交回复
热议问题