【问题标题】:How to add 2 minutes in given time (HH:MM:SS) in Node?如何在节点中的给定时间(HH:MM:SS)添加 2 分钟?
【发布时间】:2019-05-22 11:59:25
【问题描述】:

我有一个时间说,例如:10:59:02 现在我需要在这里添加 2 分钟,它应该给我 11:01:02 的时间。我试过但没能实现 谁能帮我解决这个问题?

【问题讨论】:

标签: javascript node.js time momentjs


【解决方案1】:

尝试使用矩库。

var date = moment('10:59:02 PM', 'hh:mm:ss A')
    .add(2, 'minutes')
    .format("hh:mm:ss");
console.log(date);
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.7.0/moment.min.js" type="text/javascript"></script>

【讨论】:

    【解决方案2】:

    实际上,您需要在 Unix 时间戳中转换时间/日期,然后您可以添加分钟,然后再次在 Date 构造函数中传递该时间戳。您可以根据需要获得时间。

    var unixTimestamp = Math.round(new Date("2019-05-22 15:10:00").getTime()/1000); // convert to unixtimestamp
    console.log(unixTimestamp);
    
    unixTimestamp += 120 // added 2 min
    date = new Date(unixTimestamp * 1000); // again convert to date
    console.log(date); // got your solution.

    【讨论】:

    • 在代码旁边添加一些解释总是一个好习惯
    猜你喜欢
    • 2018-07-04
    • 2010-09-20
    • 1970-01-01
    • 2021-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-14
    • 1970-01-01
    相关资源
    最近更新 更多