我有time1 = '09:00 AM'
和time2 = '06:30 PM'
。
我如何使用moment.js减去这两个,这样我得到了result = 9hrs 30mins
。
我在互联网上搜索但找不到合适的解决方案。 任何建议都非常感谢。
答案 0 :(得分:0)
我建议您编写自己的自定义函数,将时间转换为24小时,如果是PM则添加12小时,如果是AM则添加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
这应该有效。如果您有任何疑问,请随时提出。