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

Extract time (HH:MM) from moment timezone conversion

本文关键字:HH MM 取时间 提取 时刻 时区 转换      更新时间:2023-09-26

此代码使用node.js即时时区获取纽约时间。

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')即可。这应该行得通。

@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

以下将起作用:

$(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文档。

编辑:

略有差异:

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

归功于Matt Johnson