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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.