tags:

views:

294

answers:

4

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        
+4  A: 
$time = strtotime('10:00');
$startTime = date("H:i", strtotime('-30 minutes', $time));
$endTime = date("H:i", strtotime('+30 minutes', $time));
webbiedave
Many thanks, can't believe I didn't think to do that!
bateman_ap
You're welcome. Glad I could help.
webbiedave
+2  A: 

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');
Gordon
Would +1 for mentioning `DateTime` if I hadn't already +1'd.
Pekka
Thanks for the DateTime headsup, will have to read up about it...
bateman_ap
A: 

I usually take a slightly different tack:

$startTime = date("H:i",time() - 1800); $endTime = date("H:i",time() + 1800);

Where 1800 seconds = 30 minutes.

Hans
A: 

Your current solution does not work because $time is a string - it needs to be a Unix timestamp. You can do this instead:

$unix_time = strtotime('January 1 2010 '.$time); // create a unix timestamp
$startTime date( "H:i", strtotime('-30 minutes', $unix_time) );
$endTime date( "H:i", strtotime('+30 minutes', $unix_time) );
DisgruntledGoat