Skip to content

Instantly share code, notes, and snippets.

@alDuncanson
Created April 20, 2020 17:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alDuncanson/f9d06ea85196f0cbe1abaa2f5420e2f5 to your computer and use it in GitHub Desktop.
Save alDuncanson/f9d06ea85196f0cbe1abaa2f5420e2f5 to your computer and use it in GitHub Desktop.
Convert military and standard times
// 3:30 pm => 15:30
const standardToMilitary = standardTime => {
const [time, period] = standardTime.split(' ')
const [hours, minutes] = time.split(':')
if (period === 'am') {
return `${hours == 12 ? 24 : hours}:${minutes}`
} else {
return `${parseInt(hours) === 12 ? 12 : parseInt(hours) + 12}:${minutes}`
}
}
// 15:30 => 3:30 pm
const militaryToStandard = time => {
const [hours, minutes] = time.split(':')
if (parseInt(hours) < 12 || parseInt(hours) === 24) {
return `${hours == 0 || hours == 24 ? 12 : hours}:${minutes} am`
} else {
return `${hours % 12 === 0 ? 12 : hours % 12}:${minutes} pm`
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment