I'd like to add 2 values from MySQL database in an php app. One is stored as a Datetime type, the other one as Time.
$datetime; // "2013-02-08 14:00:00"
$time; // "01:00:00"
I'd like to add 1 hour to $datetime, this doesn't give me the correct result:
$newdatetime = strtotime($datetime) + strtotime($time);
echo date('Y-m-d H:i:s', $newdatetime); // "1920-02-11 08:31:44"
How can I do this correctly?
Hmm I've dealt with it this way:
$datetime = "2013-02-08 14:00:00";
$time = "01:00:00"; //not always 1 hour, value from db
$t = explode(":",$time); // array(01,00,00)
$hour = mktime($t['0'],$t['1'],$t['2'],1,1,1970); // 3600
$newdatetime = strtotime($datetime) + $hour;
echo date("Y-m-d H:i:s",$added); // "2013-02-08 15:00:00"
Not the most elegant way, but works! As I'm looking now it's simmilar to One Trick Pony's solution, only not objective.
$dt = new DateTime("2013-02-08 14:00:00");
$dt->modify('+1 hour');
echo $dt->format('Y-m-d H:i:s');
$datetime = DateTime::createFromFormat('Y-m-d H:i:s', $datetime);
// extract H, M, S
$time = sscanf($time, '%d:%d:%d');
// build date interval string
$time = vsprintf('PT%dH%dM%dS', $time);
// add it to your date
$datetime->add(new DateInterval($time));
print $datetime->format('Y-m-d H:i:s');
But if $time
is always one hour, John Conde's solution would be a better choice :P