Time calculation in php (add 10 hours)?

后端 未结 7 873
悲哀的现实
悲哀的现实 2020-12-03 03:18

I get the time:

$today = time();
$date = date(\'h:i:s A\', strtotime($today));

if the current time is \"1:00:00 am\", how do i add 10 more

7条回答
  •  醉梦人生
    2020-12-03 03:46

    In order to increase or decrease time using strtotime you could use a Relative format in the first argument.

    In your case to increase the current time by 10 hours:

    $date = date('h:i:s A', strtotime('+10 hours'));
    

    In case you need to apply the change to another timestamp, the second argument can be specified.

    Note:

    Using this function for mathematical operations is not advisable. It is better to use DateTime::add() and DateTime::sub() in PHP 5.3 and later, or DateTime::modify() in PHP 5.2.

    So, the recommended way since PHP 5.3:

    $dt = new DateTime(); // assuming we need to add to the current time
    $dt->add(new DateInterval('PT10H'));
    $date = $dt->format('h:i:s A');
    

    or using aliases:

    $dt = date_create(); // assuming we need to add to the current time
    date_add($dt, date_interval_create_from_date_string('10 hours')); 
    $date = date_format($dt, 'h:i:s A');
    

    In all cases the default time zone will be used unless a time zone is specified.

提交回复
热议问题