javascript 如何在javascript中执行日期减法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5075336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to perform date subtraction in javascript
提问by Jinbom Heo
It's a little complicated to calculate delta time in js. this is the pseudo-code,
在js中计算delta时间有点复杂。这是伪代码,
var atime = "2010-12-05T08:03:22Z";
var btime = "2010-01-11T08:01:57Z"
var delta_time = btime - atime;
delta_time ?
I want to know exact date time between two time inputs. is there any easy way to find out delta time?
我想知道两个时间输入之间的确切日期时间。有没有什么简单的方法可以找出增量时间?
回答by dxh
var atime = new Date("2010-12-05T08:03:22Z");
var btime = new Date("2010-01-11T08:01:57Z");
var delta_time = btime - atime;
The value of delta_time will be the difference between the two dates in milliseconds.
delta_time 的值是以毫秒为单位的两个日期之间的差值。
If you're only interested in the difference, and don't care to differentiate between which is the later date, you might want to do
如果你只对差异感兴趣,而不关心区分哪个是较晚的日期,你可能想要做
var delta_time = Math.abs(btime - atime);
回答by pduersteler
In my opinion, a Date / Time object displays a time in a current situation (e.g. now() ). Displaying a difference of time is not part of a Date or Time object because the difference between e.g. May 1 and May 3 would result in, maybe, January 3, 1970, or maybe May 2, depends on how you start counting your delta on.
在我看来,日期/时间对象显示当前情况下的时间(例如 now() )。显示时间差异不是日期或时间对象的一部分,因为例如 5 月 1 日和 5 月 3 日之间的差异可能会导致 1970 年 1 月 3 日或 5 月 2 日,这取决于您如何开始计算增量。
I would suggest putting your times into a timestamp which is a simple int in seconds. Do some substraction and voilá, there's your delta seconds. This delta can be used to apply to any other Object.
我建议将您的时间放入时间戳中,这是一个以秒为单位的简单整数。做一些减法和瞧,这是你的增量秒。此增量可用于应用于任何其他对象。

