如何在JavaScript中的两个日期之间获得区别? [英] How do I get the difference between two Dates in JavaScript?

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

问题描述

我正在创建一个应用程序,它允许您使用时间框架定义事件。我想自动填写用户选择或更改开始日期的结束日期。然而,我不能弄清楚两个方面的差异,然后如何创建一个新的结束日期使用这种差异。

I'm creating an application which lets you define events with a time frame. I want to automatically fill in the end date when the user selects or changes the start date. I can't quite figure out, however, how to get the difference between the two times, and then how to create a new end Date using that difference.

推荐答案

在JavaScript中,日期可以通过调用 getTime()方法转换为自epoc以来的毫秒数只需使用数字表达式中的日期。

In JavaScript, dates can be transformed to the number of milliseconds since the epoc by calling the getTime() method or just using the date in a numeric expression.

所以要得到差异,只需减去两个日期。

So to get the difference, just subtract the two dates.

要根据差异创建一个新的日期,只需传递构造函数中的毫秒数。

To create a new date based on the difference, just pass the number of milliseconds in the constructor.

var oldBegin = ...
var oldEnd = ...
var newBegin = ...

var newEnd = new Date(newBegin + oldEnd - oldBegin);

这应该只是工作

编辑:修正由@bdukes指出的错误

EDIT: Fixed bug pointed by @bdukes

编辑

有关行为的解释, oldBegin oldEnd newBegin 日期实例。调用运算符 + - 将触发Javascript自动转换,并将自动调用 valueOf() 这些对象的原型方法。发生在 valueOf()方法在 Date 对象中实现,作为调用 getTime()

For an explanation of the behavior, oldBegin, oldEnd, and newBegin are Date instances. Calling operators + and - will trigger Javascript auto casting and will automatically call the valueOf() prototype method of those objects. It happens that the valueOf() method is implemented in the Date object as a call to getTime().

所以基本上是: date.getTime()=== date.valueOf()== =(0 + date)===(+ date)

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

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