JavaScript中的日期减法 [英] Date subtraction in JavaScript
问题描述
我有两个文本框分别以YYYY / MM / DD格式接受开始日期
和结束日期
I have two text boxes which accept Start Date
and End Date
respectively, in format YYYY/MM/DD.
如果他选择的结束日期超过了50天的开始日期,我需要提醒用户。
I need to alert the user if he selects an end date that exceeds the start date by 50 days.
这是我到目前为止:
var startDate = new Date(document.getElementsByName('MYSTARTDATE').value);
var endDate = new Date(document.getElementsByName('MYENDDATE').value);
if ((endDate - startDate) > 50)
{
alert('End date exceeds specification');
return false;
}
只要举个例子,当我选择开始日期为 2012/01/22
和结束日期为 2012/02/29
Just as an example, when I select Start Date as 2012/01/22
and End Date as 2012/02/29
startDate = 'Sun Jan 22 00:00:00 UTC +0530 2012'
endDate = 'Wed Feb 29 00:00:00 UTC +0530 2012'
而 endDate - startDate
的结果是 3283200000
,而不是 38
。我做错了什么?
And the result for endDate - startDate
is 3283200000
, instead of 38
.What am I doing wrong?
推荐答案
3283200000是以毫秒为单位的38天。
3283200000 is 38 days in milliseconds.
38天x 24小时x 60分钟x 60秒x 1000毫秒
38 days x 24 hours x 60 minutes x 60 seconds x 1000 milliseconds
此外,还有38天在这两个日期之间,不是39。
Also, there are 38 days between those two dates, not 39.
一个简单的解决方案是将一个变量(常数真的)定义为一天中的毫秒数:
An easy solution is to have a variable (constant really) defined as the number of milliseconds in a day:
var days = 24*60*60*1000;
在比较中使用该变量作为单位:
And use that variable as a "unit" in your comparison:
if ((endDate - startDate) > 50*days) {
...
}
这篇关于JavaScript中的日期减法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!