Adding 30 minutes to time formatted as H:i in PHP
Having a nightmare at the moment and just can't see why it isn't working
I have a value in the form H:i (ie 10:00, 13:30) etc called $time
What I want to do is create two new values, $startTime which is 30 mins before $time and $endTime which is 30 mins after $time
I have tried the following but just doesn't seem to want to work
$startTime = date("H:i",strtotime('-30 minutes',$time));
$endTime = date("H:i",strtotime('+30 minutes',$time));
If I pass through 10:00 as $time and echo out both $startTime and $endTime I get:
$startTime = 00:30
$startTime = 01:30
$time = strtotime('10:00');
$startTime = date("H:i", strtotime('-30 minutes', $time));
$endTime = date("H:i", strtotime('+30 minutes', $time));
In order for that to work $time
has to be a timestamp. You cannot pass in "10:00" or something like $time = date('H:i', '10:00');
which is what you seem to do, because then I get 0:30 and 1:30 as results too.
Try
$time = strtotime('10:00');
As an alternative, consider using DateTime (the below requires PHP 5.3 though):
$dt = DateTime::createFromFormat('H:i', '10:00'); // create today 10 o'clock
$dt->sub(new DateInterval('PT30M')); // substract 30 minutes
echo $dt->format('H:i'); // echo modified time
$dt->add(new DateInterval('PT1H')); // add 1 hour
echo $dt->format('H:i'); // echo modified time
or procedural if you don't like OOP
$dateTime = date_create_from_format('H:i', '10:00');
date_sub($dateTime, date_interval_create_from_date_string('30 minutes'));
echo date_format($dateTime, 'H:i');
date_add($dateTime, date_interval_create_from_date_string('1 hour'));
echo date_format($dateTime, 'H:i');