【问题标题】:moment.js diff date formattingmoment.js 差异日期格式
【发布时间】:2014-02-13 23:38:03
【问题描述】:

我正在使用 moment.js 并想计算两个时间戳之间的差异,然后将它们格式化并将它们显示在 div 中。

var diffTime = moment(1390310146.791877).diff( 1390309386.271075);

这给了我 760 秒,但我想这样格式化:

(days, hrs, mins, secs) 并且仅显示大于 0 的天、小时和秒。

我如何做到这一点?

【问题讨论】:

    标签: javascript date momentjs


    【解决方案1】:

    应该使用moment.duration

       let startTime = moment('09:45:20', 'h:mm:ss A').format("HH:mm:ss");
       let endTime = moment('10:30:35', 'h:mm:ss A').format("HH:mm:ss")
       var todayDate = moment(new Date()).format("MM-DD-YYYY"); //Can change, based on the requirement
       var startDate = new Date(`${todayDate} ${startTime}`);
       var endDate = new Date(`${todayDate} ${endTime}`);
       var diffTime = moment(endDate).diff(startDate);
    
       var duration = moment.duration(diffTime);
       var years = duration.years(),
        days = duration.days(),
        months = duration.months(),
        hrs = duration.hours(),
        mins = duration.minutes(),
        secs = duration.seconds();
    
    var div = document.createElement('div');
    div.innerHTML = years + ' years ' + months + 'months ' + days + ' days ' + hrs + ' hrs ' + mins + ' mins ' + secs + ' sec';
    document.body.appendChild(div);
    

    jsfiddle

    【讨论】:

    • 为了使其正常工作,您还需要几个月的时间。 months = duration.months()
    • ^ 好点。除了月份,你还需要weeks = duration.weeks() 否则,如果你把时间细分加起来,它不会匹配diff total。
    • 我加了几个月。然而,几周不是必需的,因为该时间以天为单位。
    • dayjs 是推荐的替换 moment 的库,但它的工作方式与此答案中描述的完全相同。 medium.com/datadriveninvestor/…
    【解决方案2】:

    试试这个

    var diffTime = moment(moment(1390310146.791877).diff( 1390309386.271075)).format('H m s');
    

    它将输出“5 30 0”

    编辑

    这是获得差异的简单方法。因为这两个时间应该在同一个时区。

    var a = moment(1390310146.791877);
    var b = moment(1390309386.271075);
    a.diff(b)//To get the difference in milliseconds
    a.diff(b,'seconds')//To get the difference in seconds
    a.diff(b,'minutes')//To get the difference in minutes 
    a.zone()//Get the timezone offset in minutes
    

    希望这会有所帮助。

    【讨论】:

    • 应该在 12 分 40 秒左右返回
    • 取决于本地浏览器时区。
    • 我还不确定如何获得两个时间戳之间的正确时差?
    • 如何应对浏览器时区?
    • a.diff(b) 返回 760,实际上是秒。所以 a.diff(b,'seconds') 和 a.diff(b,'minutes') 都返回 0
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-18
    • 2016-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-06
    相关资源
    最近更新 更多