两个日期之间的差异总是使用javascript给出零日

时间:2015-04-16 13:16:13

标签: javascript date

您好我正在尝试获取两个日期之间的差异,但我继续得到0作为答案,任何人都知道为什么请帮助。我的代码就像这样

  var d1 = "2015-04-30";
  var d2 = "2015-04-14";
  var startDay = new Date(d1);
  var endDay = new Date(d2);
  var millisecondsPerDay = 1000 * 60 * 60 * 24;

  var millisBetween = startDay.getTime() - endDay.getTime();
  var days = millisBetween / millisecondsPerDay;


//If I use df1 and df2 I am getting 0
  var jsondate1 = new Date(getData.startDate).toISOString();
                var jsondate2 = new Date(getData.startDate).toISOString();

                var date = new Date(jsondate1);
                var dates = new Date(jsondate2);

   var df1 = date.getFullYear()  + '-' + (date.getMonth()+1)   + '-'
 +date.getDate() ;
 var df2 = dates.getFullYear()   + '-' +(dates.getMonth()+1) 
   + '-' +dates.getDate() ;


 //If I am using the below two lines the answer is 16 but if I am using the above d1 and d2 the answer is zero 
 var d1 = "2015-4-30";// the date here is made up by console.debug(df1 )
 var d2 = "2015-4-14"; // the date here is made up by console.debug(df2 )

我不知道我在哪里做错了

3 个答案:

答案 0 :(得分:3)

查看代码段 - 显示16。

   var d1 = "2015-04-30";
                  var d2 = "2015-04-14";
                  var startDay = new Date(d1);
                  var endDay = new Date(d2);
                  var millisecondsPerDay = 1000 * 60 * 60 * 24;

                  var millisBetween = startDay.getTime() - endDay.getTime();
                  var days = millisBetween / millisecondsPerDay;
alert(days);

我认为你应该检查你的代码,因为它可以正常工作,但代码中会出现一些代码语法错误。 (可能是)

答案 1 :(得分:0)

它应该按原样工作但你可以尝试减去日期而不调用getTime():

var d1 = "2015-04-30";
var d2 = "2015-04-14";
var startDay = new Date(d1);
var endDay = new Date(d2);
var millisecondsPerDay = 1000 * 60 * 60 * 24;

var millisBetween = startDay - endDay;
var days = millisBetween / millisecondsPerDay;
alert(days);

问题更新后:

jsondate1& jsondate2正在使用相同的日期(getData.startDate)创建,因此差异为0:

var jsondate1 = new Date(getData.startDate).toISOString();
var jsondate2 = new Date(getData.startDate).toISOString();

答案 2 :(得分:0)

如果您只想要日期差异。那么最简单的方法就是。

var d1 = "2015-04-30";
var d2 = "2015-04-14";
Math.floor(( Date.parse(d1) - Date.parse(d2) ) / 86400000);