【问题标题】:Javascript write time in specific formatJavascript以特定格式写入时间
【发布时间】:2014-05-30 10:59:23
【问题描述】:

我正在使用 Javascript 和 Date.js,需要翻译时间的字符串表示形式。

我从这种格式的时间开始:

上午3:00 下午 2:30 11:00 AM

...并且需要以这种格式放置它们:

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

我想从 Date.parse() 开始,然后打印出小时、分钟和秒。但想知道是否有更优雅的方式来做到这一点,例如Date.format("HH:MM:SS")

有什么好的方法可以做到这一点?

谢谢!

编辑::::

看起来您可以在 Date.js 中使用格式说明符:http://code.google.com/p/datejs/wiki/FormatSpecifiers

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

【问题讨论】:

  • 哦,您可以使用解析!好东西。我只能用 parseExact 来做到这一点。您回答了自己的问题。
  • 我在下载错误版本的 Date.js 时遇到问题。您必须通过不在主站点上的特定区域下载它才能获得最新版本:datejs.googlecode.com/svn/trunk/build/date-en-US.js

标签: javascript parsing datetime datejs


【解决方案1】:

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>

【讨论】:

  • 这是否总是使用字符返回小时和分钟? (“02”而不是“2”)
  • 这个不使用Date.js,也不解析原始字符串,也不填充个位数的分秒。
  • 但它清楚地说明了如何做到这一点。从这里开始,继续添加一些功能以在需要时添加前导零非常容易。if (curr_min &lt; 10) { curr_min = '0' + curr_min; }
  • +1 用于在寻求帮助之前自行寻找答案
【解决方案2】:

我相信这是 OP 正在寻找的答案。 :-)

<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>

此处有关格式说明符的信息:http://code.google.com/p/datejs/wiki/FormatSpecifiers

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-15
    • 1970-01-01
    • 2017-06-04
    • 2017-10-17
    • 2016-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多