【问题标题】:Moment.js and moment timezone getting current time separated in seconds, minutes and hoursMoment.js 和 moment timezone 以秒、分钟和小时分隔当前时间
【发布时间】:2018-12-13 09:03:45
【问题描述】:

我在我的项目中引用了两个脚本:

<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(秒)的部分

但我不知道该怎么做,有人可以帮我吗?

【问题讨论】:

    标签: javascript jquery time momentjs moment-timezone


    【解决方案1】:

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

    这是最强大的显示选项。它接受一串标记并用它们对应的值替换它们。

    您可以使用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>

    【讨论】:

    • 这太棒了! Ty 这么多...我现在只需要将分钟、小时和秒分成单独的变量,我该怎么做? :D
    • @User987 您在寻找hour()minute()second() 吸气剂吗?
    • @VicenzoC 是的,就是这样
    【解决方案2】:

    添加到@VincenzoC 的答案(正如他在comment 中正确添加的那样),如果您想使用,时刻库具有特定的 Getter 小时、分钟、秒。像这样 (as dictated in the moment docs)

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

    或者如果你想继续使用format 函数,你可以像这样使用它

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

    【讨论】:

      猜你喜欢
      • 2013-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多