问题
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 hours to become 11:00:00 am??
回答1:
strtotime()
gives you a number back that represents a time in seconds. To increment it, add the corresponding number of seconds you want to add. 10 hours = 60*60*10 = 36000, so...
$date = date('h:i:s A', strtotime($today)+36000); // $today is today date
Edit: I had assumed you had a string time in $today - if you're just using the current time, even simpler:
$date = date('h:i:s A', time()+36000); // time() returns a time in seconds already
回答2:
$tz = new DateTimeZone('Europe/London');
$date = new DateTime($today, $tz);
$date->modify('+10 hours');
// use $date->format() to outputs the result.
see DateTime Class (PHP 5 >= 5.2.0)
回答3:
$date = date('h:i:s A', strtotime($today . ' + 10 hours'));
(untested)
回答4:
You can simply make use of the DateTime class , OOP Style.
<?php
$date = new DateTime('1:00:00');
$date->add(new DateInterval('PT10H'));
echo $date->format('H:i:s a'); //"prints" 11:00:00 a.m
回答5:
$date = date('h:i:s A', strtotime($today . " +10 hours"));
回答6:
Full code that shows now and 10 minutes added.....
$nowtime = date("Y-m-d H:i:s");
echo $nowtime;
$date = date('Y-m-d H:i:s', strtotime($nowtime . ' + 10 minute'));
echo "<br>".$date;
回答7:
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.
来源:https://stackoverflow.com/questions/1665702/time-calculation-in-php-add-10-hours