Moment.js 和 moment timezone 获取以秒、分钟和小时分隔的当前时间
Moment.js and moment timezone getting current time separated in seconds, minutes and hours
我在我的项目中引用了两个脚本:
<script src="http://momentjs.com/downloads/moment.js"></script>
<script src="http://momentjs.com/downloads/moment-timezone-with-data.js"></script>
现在是代码部分:
<script>
$(document).ready(function () {
var now = moment(); // current timestamp, using your machine's time zone
var nowNY = now.tz('America/New_York'); // converted to NY time zone
console.log("Current time in NYC: " + nowNY.format());
});
</script>
在控制台中显示以下内容:
Current time in NYC: 2018-12-13T03:59:13-05:00
现在我只需要提取 03(小时)59(分钟)和 13(秒)的部分
但我不知道该怎么做,有人可以帮我吗?
This is the most robust display option. It takes a string of tokens and replaces them with their corresponding values.
您可以使用 HH
00-24 小时,mm
0-59 分钟,ss
秒。
这是一个活生生的例子:
var now = moment(); // current timestamp, using your machine's time zone
var nowNY = now.tz('America/New_York'); // converted to NY time zone
console.log("Current time in NYC: " + nowNY.format('HH:mm:ss'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data-2012-2022.min.js"></script>
添加到 @VincenzoC's answer (and as he correctly added in his ), the moment library has specific Getters for hours, minutes, seconds if you want to use. Like this (as dictated in the moment docs)
var now = moment();
console.log(now.hours());
或者如果您想继续使用 format
功能,您可以像这样使用它
now.format('HH');
now.format('mm');
now.format('ss');
我在我的项目中引用了两个脚本:
<script src="http://momentjs.com/downloads/moment.js"></script>
<script src="http://momentjs.com/downloads/moment-timezone-with-data.js"></script>
现在是代码部分:
<script>
$(document).ready(function () {
var now = moment(); // current timestamp, using your machine's time zone
var nowNY = now.tz('America/New_York'); // converted to NY time zone
console.log("Current time in NYC: " + nowNY.format());
});
</script>
在控制台中显示以下内容:
Current time in NYC: 2018-12-13T03:59:13-05:00
现在我只需要提取 03(小时)59(分钟)和 13(秒)的部分
但我不知道该怎么做,有人可以帮我吗?
This is the most robust display option. It takes a string of tokens and replaces them with their corresponding values.
您可以使用 HH
00-24 小时,mm
0-59 分钟,ss
秒。
这是一个活生生的例子:
var now = moment(); // current timestamp, using your machine's time zone
var nowNY = now.tz('America/New_York'); // converted to NY time zone
console.log("Current time in NYC: " + nowNY.format('HH:mm:ss'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data-2012-2022.min.js"></script>
添加到 @VincenzoC's answer (and as he correctly added in his
var now = moment();
console.log(now.hours());
或者如果您想继续使用 format
功能,您可以像这样使用它
now.format('HH');
now.format('mm');
now.format('ss');