javascript日期减法

时间:2009-08-18 17:36:41

标签: javascript datetime date

我正在寻找一种方法在两个javascript Date对象之间进行适当的减法并得到日期增量。

这是我的方法,但它在今天的日期作为输入失败:

<script type="text/javascript">
function getDayDelta(incomingYear,incomingMonth,incomingDay){
var incomingDate = new Date(incomingYear,incomingMonth,incomingDay);
var today = new Date();

var delta = incomingDate - today;
var resultDate = new Date(delta);
return resultDate.getDate();
}
//works for the future dates:
alert(getDayDelta(2009,9,10));
alert(getDayDelta(2009,8,19));

//fails for the today as input, as expected 0 delta,instead gives 31:
alert(getDayDelta(2009,8,18));
</script>

对此更好的方法是什么?

4 个答案:

答案 0 :(得分:7)

Date构造函数中的月份数是零,你应该减去一个,我认为使用时间戳计算增量更简单:

function getDayDelta(incomingYear,incomingMonth,incomingDay){
  var incomingDate = new Date(incomingYear,incomingMonth-1,incomingDay),
      today = new Date(), delta;
  // EDIT: Set time portion of date to 0:00:00.000
  // to match time portion of 'incomingDate'
  today.setHours(0);
  today.setMinutes(0);
  today.setSeconds(0);
  today.setMilliseconds(0);

  // Remove the time offset of the current date
  today.setHours(0);
  today.setMinutes(0);

  delta = incomingDate - today;

  return Math.round(delta / 1000 / 60 / 60/ 24);
}


getDayDelta(2008,8,18); // -365
getDayDelta(2009,8,18); // 0
getDayDelta(2009,9,18); // 31

答案 1 :(得分:6)

(2009,8,18)不是8月18日。现在是9月18日。

答案 2 :(得分:5)

您可以在每个日期对象上调用getTime(),然后从较早的日期对象中减去。这将为您提供两个对象之间的毫秒数差异。从那里开始,很容易就能度过几天。

要注意几个小问题:1)夏令时,2)确保您的时间来自同一时区。

答案 3 :(得分:0)

这样可以更好地工作,但它不能正确处理负面结果值。您可能希望自己简单地解析这些值并处理它们。

function getDayDelta(incomingYear,incomingMonth,incomingDay){
var incomingDate = new Date(incomingYear,incomingMonth-1,incomingDay);
var today =   new Date();
today = new Date(Date.parse(today.format("yyyy/MM/dd")));

var delta = incomingDate - today;
if (delta == 0) { return 0; }
var resultDate = new Date(delta);
return resultDate.getDate();
}
//works for the future dates:
alert(getDayDelta(2009,9,10));
alert(getDayDelta(2009,8,19));
alert(getDayDelta(2009, 8, 18));