Addition

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
aceconcepts
DevNet Resident
Posts: 1424
Joined: Mon Feb 06, 2006 11:26 am
Location: London

Addition

Post by aceconcepts »

Hi,

How can i increment a time by 5minutes?

e.g. how do i add 5minutes to a time such as 0800?

I want the results to be 0805.

Thanks.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Code: Select all

[feyd@home]>php -r "echo '0800' + 5;"
805
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Post by Christopher »

Untested and the hard way:

Code: Select all

function add_minutes_to_time($time, $delta) {
     if (strlen($time) == 4) {
          $dminutes = $delta % 60;
          $dhours = (int)($delta / 60);
          if ($dhours > 23) {
               $dhours = $dhours % 24;
          }
          $hour = substr($time, 0, 2);
          $minute = substr($time, 2, 2);
          $minute += $dminutes;
          if ($minute > 59) {
               $minute -= 60;
               ++$hour;
          }
          $hour += $dhours;
          if ($hour > 23) {
               $hour -= 24;
          }
          return sprintf('%02u%02u', $hour, $minute);
     }
     return '';
}
(#10850)
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Post by alex.barylski »

Depends on the format of the TIME I guess. If it's a timestamp then simple math is all that is needed.

Code: Select all

$time = $time + ($mins*60);
If it's not a timestamp, then convert it to one first and perform basic arithmetic - thats what I would do :)
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

I like strtotime

Code: Select all

$ts = strtotime('0800 + 5 minutes');
echo date('Y-m-d H:i:s', $ts);
Post Reply