Question

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.

Was it helpful?

Solution

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")));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top