开发者

Javascript write time in specific format

开发者 https://www.devze.com 2023-03-19 18:44 出处:网络
I\'m using Javascript along with Date.js and need to translate string representations of times. I\'m starting with times in this 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")开发者_JAVA百科.toString("HH:mm:ss");


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>


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号