如何计算两个日期之间的秒数? [英] How do I calculate how many seconds between two dates?

查看:56
本文介绍了如何计算两个日期之间的秒数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有两个日期 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)

这篇关于如何计算两个日期之间的秒数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆