javascript日期减法 [英] javascript date subtraction

查看:114
本文介绍了javascript日期减法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种在两个JavaScript Date对象之间进行适当减法并获取日增量的方法。

I am looking for a way to do proper subtraction between two javascript Date objects and get the day delta.

这是我的方法,但是今天的日期不成一个输入:

This is my approach but it fails for todays date as an input:

<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>

这将是一个更好的方法?

What would be a better approach for this ?

推荐答案

Date构造函数中的月份号为零,您应该减1,我认为使用时间戳计算增量更简单:

The month number in the Date constructor function is zero based, you should substract one, and I think that is simplier to calculate the delta using the timestamp:

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

这篇关于javascript日期减法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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