Convert time to 24 hours format in Javascript

117,161

Solution 1

new Date("2000-01-01 10:30 AM").getHours() // 10

This is 24 hours:

new Date("2000-01-01 10:30 PM").getHours() // 22

If you want a more general thing:

function get_hours(time_string) {
    return new Date("2000-01-01 " + time_string).getHours() // 22
}

Solution 2

In moment.js you can do:

theDate.format("H:MM")

Take a look here for more details: http://blog.stevenlevithan.com/archives/date-time-format

Share:
117,161
Manfredi
Author by

Manfredi

Very Cool :)

Updated on September 23, 2020

Comments

  • Manfredi
    Manfredi over 3 years

    How can I isolate and convert the local time format in JavaScript's new Date() to a 24 hour format?

    Example: 2016-09-22T23:21:56.027Z just becomes 22:56 in local time.

  • Hardipsinh Jadeja
    Hardipsinh Jadeja almost 7 years
    It requires moment.js to include. without it does not work
  • Kirit Modi
    Kirit Modi almost 5 years
    @HardipsinhJadeja how can it , Can you send code in comment.
  • 255.tar.xz
    255.tar.xz almost 5 years
    This is correct
  • T.Woody
    T.Woody over 4 years
    Sorry, but this does not right pad the hours if the hour is a single digit. That is, new Date('2019-01-01 00:00').getHours() === 0