从时刻时区转换中提取时间 (HH:MM)

Extract time (HH:MM) from moment timezone conversion

此代码使用 node.js moment-timezone 来获取纽约时间。

var moment = require('moment-timezone');
var time_output= moment().tz("America/New_York").format();

time_output 看起来像这样 2015-11-12T05:09:49-05:00

我想将 time_output 格式化为 (HH:MM) 并且看起来像 05:09.

只需将您的 .format('zz') 更改为 .format('hh:mm')。 这应该有效。

以下方法可行:

$(function() {
  var datestring = moment().tz("America/New_York").format("HH:mm");
  $("#result").append(datestring);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="http://momentjs.com/downloads/moment-with-locales.min.js"></script>
<script src="http://momentjs.com/downloads/moment-timezone-with-data-2010-2020.min.js"></script>
<div id="result"><div>

编辑:

有关格式选项的更多信息,您可以查看 momentjs docs

编辑:

细微差别:

  • h - 24 小时制
  • H - 与 A
  • 一起使用的 12 小时时间

感谢马特·约翰逊

@Margus 因在此处找到针对该案例的文档而获得赞誉: http://momentjs.com/docs/#/parsing/

您的具体问题可以使用如下代码解决:

var moment = require('moment-timezone');
var time_output= moment().tz("America/New_York").format("HH:mm");

对于缺少文档的未来信息搜索,单元测试通常会提供对图书馆用例的有用见解。

momentjs 的测试提供了一个有用的例子: https://github.com/moment/moment/blob/develop/src/test/moment/format.js

如果没有可用的单元测试(呃哦!)或者您需要说明可以参考源代码。碰巧 momentjs 源代码的结构非常适合这种发现。

日期格式在源代码中作为正则表达式: https://github.com/moment/moment/blob/develop/src/lib/format/format.js#L3