获取两个日期时间之间的时间差

282
如何计算两个时间之间的差异?例如:
var now  = "04/09/2013 15:00:00";
var then = "04/09/2013 14:20:30";

//expected result:
"00:39:30"

我试过了。
var now = moment("04/09/2013 15:00:00");
var then = moment("04/09/2013 14:20:30");

console.log(moment(moment.duration(now.diff(then))).format("hh:mm:ss"))
//outputs 10:39:30

那里的"10"是什么意思?我现在是在UTC-0300时区。执行moment.duration(now.diff(then))的结果是一个内部值正确的持续时间。
 days: 0
 hours: 0
 milliseconds: 0
 minutes: 39
 months: 0
 seconds: 30
 years: 0

如何将momentjs的持续时间转换为时间间隔?我可以使用:
duration.get("hours") +":"+ duration.get("minutes") +:+ duration.get("seconds")

但是有没有更优雅的东西呢?现在是:
Tue Apr 09 2013 15:00:00 GMT-0300 (E. South America Standard Time)…}

moment(moment.duration(now.diff(then))) 是:
Wed Dec 31 1969 22:39:30 GMT-0200 (E. South America Daylight Time)…}

数值为-0200,因为在1969年12月31日使用了夏令时。

4
“但我确定我不喜欢约会” :P 你有没有读过这个:http://nodatime.org/unstable/userguide/trivia.html? - Boris Callens
22个回答

2
在 ES8 中使用 moment,now 和 start 都是 moment 对象。
const duration = moment.duration(now.diff(start));
const timespan = duration.get("hours").toString().padStart(2, '0') +":"+ duration.get("minutes").toString().padStart(2, '0') +":"+ duration.get("seconds").toString().padStart(2, '0');

2

Typescript:以下代码应该可以正常运行,

export const getTimeBetweenDates = ({
  until,
  format
}: {
  until: number;
  format: 'seconds' | 'minutes' | 'hours' | 'days';
}): number => {
  const date = new Date();
  const remainingTime = new Date(until * 1000);
  const getFrom = moment([date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()]);
  const getUntil = moment([remainingTime.getUTCFullYear(), remainingTime.getUTCMonth(), remainingTime.getUTCDate()]);
  const diff = getUntil.diff(getFrom, format);
  return !isNaN(diff) ? diff : null;
};

1
这将返回最大时间差,例如(4秒,2分钟,1小时,2天,3周,4个月,5年)。 我用它来通知最近的时间。
function dateDiff(startDate, endDate) {
    let arrDate = ["seconds", "minutes", "hours", "days", "weeks", "months", "years"];
    let dateMap = arrDate.map(e => moment(endDate).diff(startDate, e));
    let index = 6 - dateMap.filter(e => e == 0).length;
    return {
        type: arrDate[index] ?? "seconds",
        value: dateMap[index] ?? 0
    };
}


例子:

dateDiff("2021-06-09 01:00:00", "2021-06-09 04:01:01")

{type: "hours", value: 3}

dateDiff("2021-06-09 01:00:00", "2021-06-12 04:01:01")

{type: "days", value: 3}

dateDiff("2021-06-09 01:00:00", "2021-06-09 01:00:10")

{type: "seconds", value: 10}


1
以下方法适用于所有情况(日期之间的差异小于24小时和大于24小时的差异):
// Defining start and end variables
let start = moment('04/09/2013 15:00:00', 'DD/MM/YYYY hh:mm:ss');
let end   = moment('04/09/2013 14:20:30', 'DD/MM/YYYY hh:mm:ss');

// Getting the difference: hours (h), minutes (m) and seconds (s)
let h  = end.diff(start, 'hours');
let m  = end.diff(start, 'minutes') - (60 * h);
let s  = end.diff(start, 'seconds') - (60 * 60 * h) - (60 * m);

// Formating in hh:mm:ss (appends a left zero when num < 10)
let hh = ('0' + h).slice(-2);
let mm = ('0' + m).slice(-2);
let ss = ('0' + s).slice(-2);

console.log(`${hh}:${mm}:${ss}`); // 00:39:30

1
日期时间输入
    var dt1 = new Date("2019-1-8 11:19:16");
    var dt2 = new Date("2019-1-8 11:24:16");


    var diff =(dt2.getTime() - dt1.getTime()) ;
    var hours = Math.floor(diff / (1000 * 60 * 60));
    diff -= hours * (1000 * 60 * 60);
    var mins = Math.floor(diff / (1000 * 60));
    diff -= mins * (1000 * 60);


    var response = {
        status : 200,
        Hour : hours,
        Mins : mins
    }

OUTPUT

{
"status": 200,
"Hour": 0,
"Mins": 5
}

0

上班时间=06:38,下班时间=15:40

 calTimeDifference(){
        this.start = dailyattendance.InTime.split(":");
        this.end = dailyattendance.OutTime.split(":");
        var time1 = ((parseInt(this.start[0]) * 60) + parseInt(this.start[1]))
        var time2 = ((parseInt(this.end[0]) * 60) + parseInt(this.end[1]));
        var time3 = ((time2 - time1) / 60);
        var timeHr = parseInt(""+time3);
        var  timeMin = ((time2 - time1) % 60);
    }

0
我使用 TypeScript 创建了一个简单的函数。
const diffDuration: moment.Duration = moment.duration(moment('2017-09-04 12:55').diff(moment('2017-09-02 13:26')));
setDiffTimeString(diffDuration);

function setDiffTimeString(diffDuration: moment.Duration) {
  const str = [];
  diffDuration.years() > 0 ? str.push(`${diffDuration.years()} year(s)`) : null;
  diffDuration.months() > 0 ? str.push(`${diffDuration.months()} month(s)`) : null;
  diffDuration.days() > 0 ? str.push(`${diffDuration.days()} day(s)`) : null;
  diffDuration.hours() > 0 ? str.push(`${diffDuration.hours()} hour(s)`) : null;
  diffDuration.minutes() > 0 ? str.push(`${diffDuration.minutes()} minute(s)`) : null;
  console.log(str.join(', '));
} 
// output: 1 day(s), 23 hour(s), 29 minute(s)

生成 JavaScript 的代码:https://www.typescriptlang.org/play/index.html

0

使用moment非常简单,下面的代码将返回当前时间与指定时间之间的小时差:

moment().diff('2021-02-17T14:03:55.811000Z', "h")

0
const getRemainingTime = (t2) => {
  const t1 = new Date().getTime();
  let ts = (t1-t2.getTime()) / 1000;

  var d = Math.floor(ts / (3600*24));
  var h = Math.floor(ts % (3600*24) / 3600);
  var m = Math.floor(ts % 3600 / 60);
  var s = Math.floor(ts % 60);

  console.log(d, h, m, s)

}

请不要只发布代码答案,而是添加一些文本说明您的方法如何工作以及它与其他给出答案的不同之处。您还可以查看我们的“如何撰写好答案”条目。 - ahuemmer

0

使用Moment.js计算时间戳差异:

获取两个时间戳之间的差异:

Syntax: moment.duration(moment(moment(date1).diff(moment(date2)))).asHours()

小时差异: moment.duration(moment(moment(1590597744551).diff(moment(1590597909877)))).asHours()

分钟差异: moment.duration(moment(moment(1590597744551).diff(moment(1590597909877)))).asMinutes().toFixed()

注意:如果您需要精确值,可以删除.toFixed()

代码:

const moment = require('moment')

console.log('Date 1',moment(1590597909877).toISOString())
console.log('Date 2',moment(1590597744551).toISOString())
console.log('Date1 - Date 2 time diffrence is : ',moment.duration(moment(moment(1590597909877).diff(moment(1590597744551)))).asMinutes().toFixed()+' minutes')

请参考以下工作示例: https://repl.it/repls/MoccasinDearDimension


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接