Search code examples
javascriptparsingdatetimedatejs

Javascript write time in specific format


I'm using Javascript along with Date.js and need to translate string representations of times.

I'm starting with times in this format:

3:00am
2:30pm 
11:00am

...and need to put them in this format:

03:00:00
14:00:00
11:00:00

I was thinking of starting with Date.parse() and then printing out the hours, minutes, and seconds. But was wondering if there is a more elegant way to do this such as something along the lines of Date.format("HH:MM:SS")

What is a good way to do this?

Thanks!

Edit::::

It looks like you can use the format specifiers with Date.js: http://code.google.com/p/datejs/wiki/FormatSpecifiers

Date.parse("3:00am").toString("HH:mm:ss");

Solution

  • I believe this is the answer the OP is looking for. :-)

    <html>
      <head>
        <title>Show US Times in 24h form with Date.js</title>
      </head>
      <body>
        <script type="text/javascript" src="date.js"></script>  
        <script>
          var d = Date.parseExact("2:30pm", "h:mmtt");
          document.write(d.toString("HH:mm:ss"));
        </script>
      </body>
    </html>
    

    Info on format specifiers here: http://code.google.com/p/datejs/wiki/FormatSpecifiers