【问题标题】:How can we subtract time using moment,js?我们如何使用 moment,js 减去时间?
【发布时间】:2017-04-29 11:52:32
【问题描述】:

我有time1 = '09:00 AM'time2 = '06:30 PM'。 如何使用 moment.js 减去这两个,这样我得到result = 9hrs 30mins

我在互联网上进行了搜索,但找不到合适的解决方案。 任何建议都非常感谢。

【问题讨论】:

标签: javascript momentjs


【解决方案1】:

我建议编写您自己的自定义函数,将时间转换为 24 小时,如果是下午则增加 12 小时,如果是上午则为 0。然后它将时间转换为分钟,减去两次,然后将它们转换回 HH:MM AM/PM。

(伪代码(读起来有点像javascript))

//ap = am or pm; 0 for am, 1 for pm
define "subtractTimes" (time1, time1ap, time2, time2ap):

    //gets the length of time1 and time2
    set "time1Length" to (length(time1))
    set "time2Length" to (length(time2))

    //adds 12 hours if pm, converted to minutes
    set "time1InMinutes" to (time1ap * (12 * 60))
    set "time2InMinutes" to (time2ap * (12 * 60))

    //gets minutes from time1 and time2
    //You'd have to program your own function "getLetters"
    //Unless there's one that I'm unaware of. 
    set "time1MM" to (getLetters(time1,(time1Length-1),time1Length))
    set "time2MM" to (getLetters(time2,(time2Length-1),time2Length))


    //this script makes sure the times are the proper length.
    if "time1Length" = (4)
        set "time1" to (("0")join(time1)
    if "time2Length" = (4)
        set "time2" to (("0")join(time2)

    //gets hours from time1 and time 2
    set "time1HH" to (getLetters(time1,(time1Length-4),time1Length-3))
    set "time2HH" to (getLetters(time2,(time2Length-4),time2Length-3))

    //puts it all together
    set "time1InMinutes" to (time1InMinutes+(time1HH*60)+time1MM)
    set "time2InMinutes" to (time2InMinutes+(time2HH*60)+time2MM)
    set "newTimeInMinutes" to ((time1InMinutes)-(time2InMinutes))

    //converts it to HH:MM AM/PM
    set "newTime" to (floor(newTimeInMinutes/60))
    set newTimeInMinutes" to (newTimeInMinutes-(newTime*60))
    if "newTime" > (12): 
        set "newTime" to (newTime-12)
        set "ap" to (AM)
    else
        set "ap" to (PM)
    set "newTime" to ((newTime)join(":")join(newTimeInMinutes))
    set "newTime" to ((newTime)join(" ")join(ap)

    //end

这应该可行。如果您有任何问题,请随时提出。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-09
    • 2021-10-15
    • 2019-09-07
    • 1970-01-01
    • 2020-02-05
    • 2021-09-16
    • 2018-04-17
    相关资源
    最近更新 更多