Get the time difference between two datetimes

前端 未结 19 2267
花落未央
花落未央 2020-11-22 05:25

I know I can do anything and some more envolving Dates with momentjs. But embarrassingly, I\'m having a hard time trying to do something that seems simple: geting the differ

19条回答
  •  滥情空心
    2020-11-22 06:08

    Your problem is in passing the result of moment.duration() back into moment() before formatting it; this results in moment() interpreting it as a time relative to the Unix epoch.

    It doesn't give you exactly the format you're looking for, but

    moment.duration(now.diff(then)).humanize()

    would give you a useful format like "40 minutes". If you're really keen on that specific formatting, you'll have to build a new string yourself. A cheap way would be

    [diff.asHours(), diff.minutes(), diff.seconds()].join(':')

    where var diff = moment.duration(now.diff(then)). This doesn't give you the zero-padding on single digit values. For that, you might want to consider something like underscore.string - although it seems like a long way to go just for a few extra zeroes. :)

提交回复
热议问题