如何计算两个日期之间的秒数?

问题描述:

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

So I have two dates YYYY-MM-DD and ZZZZ-NN-EE

我怎样才能知道它们之间有多少秒?

How can I find out how many seconds there are between them?

I'm take YYYY &ZZZZ 表示整数值,表示年份,MM &NN 表示整数值,表示一年中的月份和 DD &EE 作为整数值表示一个月中的某一天.

I'm taking YYYY & ZZZZ to mean integer values which mean the year, MM & NN to mean integer values meaning the month of the year and DD & EE as integer values meaning the day of the month.

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 站点

A handy source for future reference is the MDN site

或者,如果您的日期采用 javascript 可以解析的格式

Alternatively, if your dates come in a format javascript can parse

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

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

and then you can use that value as the difference in milliseconds (dif in both my examples has the same meaning)