views:

36

answers:

1

So what I am trying to do is add two strings together in the form of military time. Here is the example.

Time1 = "01:00"; Time2 = "04:30";

Adding the two together would produce "05:30". This seems incredibly simple, but it has been a long long day for a new learner. Any help would be greatly appreciated.

+1  A: 

You can do something like this in PHP 5.3:

$d = new DateTime("01:00");
$f = $d->add(new DateInterval("PT04H30M"));
echo $f->format("H:i"); //outputs 05:30

Converting 04:30 to PT04H30M should be trivial. Note that whether this is actually what you want depends on what you mean by "04:30". This code may or may not sum 4*60+30 minutes to the actual time.

If you mean "4 hours and 30 minutes on the clock" this is always correct. However, if you mean "4*60+30 minutes", it depends on the day and timezone. Example:

$d = new DateTime("2010-03-28 01:00 Europe/Lisbon");
$f = $d->setTimestamp($d->getTimestamp() + (4*60+30)*60);
echo $f->format("H:i"); //outputs 06:30 due to DST

An alternate implementation of the last case (assuming current day and default timezone) for PHP 5.2 is

echo date("H:i", strtotime("+4 hours +30 mins", strtotime("01:00")));

For the first case, we must do:

date_default_timezone_set("UTC");
echo date("H:i", strtotime("+4 hours +30 mins", strtotime("01:00")));
Artefacto
And say my host hasn't update to 5.3? Any suggestions (Beyond the obvious of switching hosts!)
Brian Lang
@Brian I've added solutions for PHP 5.2.
Artefacto
You sir, are fantastic! Exactly what I was looking for. I honestly spent a good 45 minutes on Google searching to no end. Much appreciated.
Brian Lang
So I just went to implement this - The addition part works great. If I use that code exactly how it is written for say '13:45' + '02:30' the code produces '16:15'. However, if I use subtraction, the result is off by one hour. For example, '13:45' - '02:30' produces '12:15'. It is the same code you have above but with a MINUS symbol rather than PLUS. Any ideas?
Brian Lang
@Brian No, it's `echo date("H:i", strtotime("-2 hours -30 mins", strtotime("13:45")));`. The + sign actually has no effect.
Artefacto