Last active
October 24, 2017 15:31
-
-
Save Akahadaka/c26b55ad5994d57e6a2e534765d1038b to your computer and use it in GitHub Desktop.
Manipulate date formatting
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
function main(value) { | |
// Add a fake date since we're just working with time | |
const epoch = '1970-01-01'; | |
// Convert the given time to a Date Object | |
dateVal = new Date(`${epoch} ${value}`); | |
// Manually determine the suffix for "am" or "pm" since I have found no support in JS | |
ampm = (dateVal.getHours() - 12 < 0) ? 'am' : 'pm'; | |
// And manually adjust the time to a 12 hour system | |
if (ampm == 'pm') { | |
dateVal.setHours(dateVal.getHours() - 12); | |
} | |
// There must be a better way to format the time of a Date Object... | |
// something like return Date(dateVal, "hh:mm:ss"); | |
//return `${dateVal.getHours()}:${dateVal.getMinutes()}:${dateVal.getSeconds()} ${ampm}`; | |
// Use the built in TimeString, but format to use our "am" or "pm" system instead | |
return dateVal.toTimeString().replace(/\s.*/, ' ') + ampm; | |
} | |
// Test the main function | |
console.log(main("09:00:00") == "09:00:00 am"); | |
console.log(main("21:00:00") == "09:00:00 pm"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment