1

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");
2
  • Oh you got it to work with parse! Nice one. I could only do it with parseExact. You answered your own question. Commented Jul 12, 2011 at 0:08
  • 1
    I had issues with downloading the wrong version of Date.js. You have to download it through this specific area thats not on the main site to get the most updated version: datejs.googlecode.com/svn/trunk/build/date-en-US.js Commented Jul 12, 2011 at 2:36

2 Answers 2

3

The answer to all your questions

<script type="text/javascript">
<!--

var d = new Date();
var curr_hour = d.getHours();
var curr_min = d.getMinutes();
var curr_sec = d.getSeconds();

document.write(curr_hour + ":" + curr_min + ":" + curr_sec);

//-->
</script>
Sign up to request clarification or add additional context in comments.

4 Comments

Does this return the hours and minutes always using characters? ("02" instead of "2")
This does not use Date.js, nor does it parse the original string, nor does it pad out single-digit minutes and seconds.
But it gives a clear view on how to do it. From here, it's pretty easy to go on and add some functionality to add a leading zero when needed for example.. if (curr_min < 10) { curr_min = '0' + curr_min; } etc.
+1 for looking for the answer on your own before asking for help
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.