Home
About
Blog
Media Gallery

Adding time with a decimal value


Illustrated with PHP, but meant to be language agnostic. Shows how to use simple datatypes to extract hours, minutes and seconds from a decimal value to add to other hour, minute and second integers.

<?php
// Universal non-specific language code to add decimal value as hours, 
// minutes and seconds to an existing time, using raw integer values.

function prepend_zero($i) {
	return ($i < 10 ? '0'. strval($i) : strval($i));
}

// Get hours and minutes in integers.
$time_now_h = intval(date('H'));
$time_now_m = intval(date('i'));
$time_now_s = intval(date('s'));

// Specify extra time in decimal.
$added_time = (float)1.555;

// Extract time from decimal.
$hours_added = (int)$added_time;
$minutes_added = (float)(($added_time - $hours_added) * 60);
$seconds_added = (float)(($minutes_added - (int)$minutes_added) * 60);

// Future time.
$future_hours = $time_now_h + $hours_added;
$future_minutes = $time_now_m + (int)$minutes_added;
$future_seconds = $time_now_s + (int)round($seconds_added);

// Normalize overflow.
if ($future_hours >= 24)
	$future_hours -= 24;
if ($future_seconds >= 60) {
	$future_seconds -= 60;
	$future_minutes += 1;
}
if ($future_minutes >= 60) {
	$future_minutes -= 60;
	$future_hours += 1;
}

// Show times.
echo "  Time now: ". 
     prepend_zero($time_now_h) .":". 
     prepend_zero($time_now_m) .":". 
     prepend_zero($time_now_s) ."\n".
     "Time extra: ". 
     prepend_zero($future_hours) .":". 
     prepend_zero($future_minutes) .":". 
     prepend_zero($future_seconds) ."\n".
     "Added ". 
     strval($hours_added) ." hours, ".
     strval((int)$minutes_added) ." minutes and ".
     strval((int)round($seconds_added)) ." seconds.";
?>


Result:
C:\Users\djver\Desktop>php time_plus_float.php
  Time now: 08:48:45
Time extra: 10:22:03
Added 1 hours, 33 minutes and 18 seconds.


Original Post: Sep 15th, '22 11:04 CEST.

Tags: PHP Concept Code