Jump to content

Converting Time to Integer


RyanMinor

Recommended Posts

How would I go about converting time (could be in hours:minutes:seconds, minutes:seconds, or just seconds format) into the number of seconds? I have a function that will take in hours:minutes:seconds values but when I supply only minutes:seconds or just seconds, it fails.

 

function convertTimeToSeconds($time) {
// Check the duration input of time
if (!preg_match("/^\d+(:\d{1,2})?(:\d{1,2})?$/", $time)) {
	throw new exception('Invalid input format for duration.');
}
// Retrieve hours, minutes, and seconds
$hours = substr($time, 0, -6);
$minutes = substr($time, -5, 2);
$seconds = substr($time, -2);
$total_seconds = ($hours * 3600) + ($minutes * 60) + $seconds;
// Ensure that the result is an integer
if (!is_int($total_seconds)) {
	throw new Exception('Output format is not integer.');
} else {
	return $total_seconds;
}
}

Link to comment
https://forums.phpfreaks.com/topic/267119-converting-time-to-integer/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.