如何计算两次约会之间的间隔时间?

所以我有两个日期YYYY-MM-DDZZZZ-NN-EE

我怎么知道它们之间有多少秒呢?

229965 次浏览

创建两个Date对象并对它们调用valueOf(),然后比较它们。

JavaScript Date Object Reference

我选YYYY &ZZZZ为表示年份、MM和amp的整数值;NN为表示一年中的月份和DD &的平均整数值;EE为整数值,表示一个月中的一天。

var t1 = new Date(YYYY, MM, DD, 0, 0, 0, 0);
var t2 = new Date(ZZZZ, NN, EE, 0, 0, 0, 0);
var dif = t1.getTime() - t2.getTime();


var Seconds_from_T1_to_T2 = dif / 1000;
var Seconds_Between_Dates = Math.abs(Seconds_from_T1_to_T2);

一个方便将来参考的来源是MDN网站

或者,如果你的日期以javascript可以解析的格式出现

var dif = Date.parse(MM + " " + DD + ", " + YYYY) - Date.parse(NN + " " + EE + ", " + ZZZZ);

然后您可以使用该值作为毫秒差(dif在我的两个例子中具有相同的含义)

减:

var a = new Date();
alert("Wait a few seconds, then click OK");


var b = new Date();
var difference = (b - a) / 1000;


console.log("You waited: " + difference + " seconds");

var a = new Date("2010 jan 10"),
b = new Date("2010 jan 9");


alert(
a + "\n" +
b + "\n" +
"Difference: " + ((+a - +b) / 1000)
);

如果你的一个或两个日期都在未来,那么如果你想精确到秒,恐怕你就是SOL了。UTC时间有闰秒,只有在6个月之前才知道,所以任何比这更晚的日期都可能不准确几秒(在实践中,由于人们不经常更新他们的机器,您可能会发现未来的任何时间都有几秒的误差)。

这很好地解释了设计日期/时间库的理论,以及为什么会这样

. net提供了TimeSpan类来为您进行计算。

var time1 = new Date(YYYY, MM, DD, 0, 0, 0, 0)
var time2 = new Date(ZZZZ, NN, EE, 0, 0, 0, 0)


Dim ts As TimeSpan = time2.Subtract(time1)


ts.TotalSeconds

在bash中:

bc <<< "$(date --date='1 week ago' +%s) - \
$(date --date='Sun,  29 Feb 2004 16:21:42 -0800' +%s)"

它确实需要安装bc和gnu日期。

你可以简单地做。

var secondBetweenTwoDate = Math.abs((new Date().getTime() - oldDate.getTime()) / 1000);

简单的方法:

function diff_hours(dt2, dt1)
{


var diff =(dt2.getTime() - dt1.getTime()) / 1000;
diff /= (60 * 60);
return Math.abs(Math.round(diff));


}




function diff_minutes(dt2, dt1)
{


var diff =(dt2.getTime() - dt1.getTime()) / 1000;
diff /= (60);
return Math.abs(Math.round(diff));


}


function diff_seconds(dt2, dt1)
{


var diff =(dt2.getTime() - dt1.getTime()) / 1000;
return Math.abs(Math.round(diff));


}


function diff_miliseconds(dt2, dt1)
{


var diff =(dt2.getTime() - dt1.getTime());
return Math.abs(Math.round(diff));


}




dt1 = new Date(2014,10,2);
dt2 = new Date(2014,10,3);
console.log(diff_hours(dt1, dt2));




dt1 = new Date("October 13, 2014 08:11:00");
dt2 = new Date("October 14, 2014 11:13:00");
console.log(diff_hours(dt1, dt2));


console.log(diff_minutes(dt1, dt2));


console.log(diff_seconds(dt1, dt2));


console.log(diff_miliseconds(dt1, dt2));
function parseDate(str) {
const [dateStr, timeStr] = str.split(' ');
const [m,d,y] = dateStr.split('/');
const [h,min] = timeStr.split(':');
const date = new Date(y,m,d,h,min,0, 0);
  

return date;
}


const date1 = parseDate('28/6/2022 22:55');
const date2 = parseDate('28/6/2022 22:58');
const diffInSeconds = (date2 - date1) / 1000;


console.log(diffInSeconds)