Last active
October 10, 2015 15:47
-
-
Save ronnyhaase/3713743 to your computer and use it in GitHub Desktop.
Format time by hour of the day and minute of the hour
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Returns formatted time depending on the clock (e.g. 00:00 / 12:00am) | |
* @param {number} hour - The hour of the day (0-24) | |
* @param {number} minute - The minute of the the hour (0-59) | |
* @param {string} clock - Either "12h" or "24h" | |
* @returns The time as a well formated string or false in case of an error | |
*/ | |
function formatTime(hour, minute, clock) { | |
( minute < 10 ) | |
? minute = '0' + minute | |
: minute = '' + minute | |
if ( clock === '12h' ) { | |
// Attach a.m / p.m. | |
if ( hour < 12 || hour === 24 ) | |
minute += 'am' | |
else | |
minute += 'pm' | |
// 12h clock specific transformations 00:00/24:00 -> 12 am, 12:00 -> 12:00pm | |
if ( hour === 0 ) | |
hour = 12 | |
else if ( hour === 24 ) | |
hour = 0 | |
// Decrease hour by 12 on noon | |
else if ( hour > 13 ) | |
hour -= 12 | |
} | |
hour = '' + hour | |
if (hour.length === 1) | |
hour = '0' + hour | |
return hour + ':' + minute | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment