Skip to content

Instantly share code, notes, and snippets.

@Akahadaka
Last active October 24, 2017 15:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Akahadaka/c26b55ad5994d57e6a2e534765d1038b to your computer and use it in GitHub Desktop.
Save Akahadaka/c26b55ad5994d57e6a2e534765d1038b to your computer and use it in GitHub Desktop.
Manipulate date formatting
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