简体   繁体   English

Moment.js和时刻时区将当前时间分隔为秒,分钟和小时

[英]Moment.js and moment timezone getting current time separated in seconds, minutes and hours

I have referenced two scripts into my project: 我在项目中引用了两个脚本:

<script src="http://momentjs.com/downloads/moment.js"></script>
<script src="http://momentjs.com/downloads/moment-timezone-with-data.js"></script>

And now the code part: 现在,代码部分:

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

In console this displays the following: 在控制台中,将显示以下内容:

Current time in NYC: 2018-12-13T03:59:13-05:00

Now I just need to extract the part with the 03 (hours) 59 (minutes) and 13 (seconds) 现在我只需要提取03(小时)59(分钟)和13(秒)的零件

But I'm not sure how to do this, can someone help me out? 但是我不确定该怎么做,有人可以帮我吗?

Simply use format('HH:mm:ss') 只需使用format('HH:mm:ss')

This is the most robust display option. 这是最可靠的显示选项。 It takes a string of tokens and replaces them with their corresponding values. 它接受一串标记并将其替换为其相应的值。

You can use HH for 00-24 hours, mm for 0-59 minutes and ss for seconds. 您可以将HH用作00-24小时, mm用作0-59分钟, ss用作秒。

Here a live sample: 这是一个现场样本:

 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> 

Adding to @VincenzoC 's answer (and as he correctly added in his comment ), the moment library has specific Getters for hours, minutes, seconds if you want to use. 如果要使用@MoincenzoC的答案(以及他在注释中正确添加的内容),矩量库具有特定的Getter(小时,分钟,秒)。 Like this ( as dictated in the moment docs ) 像这样( 如当前文档所规定

var now = moment(); console.log(now.hours());

Or if you want to stay with the format function you can use it like this 或者,如果您想保留format功能,可以像这样使用它

now.format('HH'); now.format('mm'); now.format('ss');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM