1

我试图从两个日期中获取天数、小时数。我搜索了解决方案并尝试了一些类似下面的代码,但它们都没有返回正确的天数,小时数为 2 天、3 小时。我的字段值如下:

d1 = '2014-10-09 08:10:56';
d2 ='2014-11-09 10:10:56';



var dateDiff = function ( d1, d2 ) {
    var diff = Math.abs(d1 - d2);
    if (Math.floor(diff/86400000)) {
        return Math.floor(diff/86400000) + " days";
    } else if (Math.floor(diff/3600000)) {
        return Math.floor(diff/3600000) + " hours";
    } else if (Math.floor(diff/60000)) {
        return Math.floor(diff/60000) + " minutes";
    } else {
        return "< 1 minute";
    }
};
function DateDiff(date1, date2) {
   var msMinute = 60*1000, 
    msDay = 60*60*24*1000,
     c = new Date(),                /* now */
    d = new Date(c.getTime() + msDay - msMinute); 
    return Math.floor(((date2 - date1) % msDay) / msMinute) + ' full minutes between'; //Convert values days and return value      
}

我在做什么错。任何帮助谢谢

4

6 回答 6

1

d1, d2在调用函数之前您是否已转换为 Date 对象dateDiff?因为如果你没有,这条线var diff = Math.abs(d1 - d2);将无法按预期工作。

更新:

我假设你的和d1格式,试试这个:d2"Y-m-d H:S:M"

function parseDate(str){
    var tmp = str.split(' ');
    var d   = tmp[0].split('-');
    var t   = tmp[1].split(':');
    return new Date(d[0], d[1]-1, d[2], t[0], t[1], t[2]);
}

function dateDiff(d1, d2){
    d1 = parseDate(d1);
    d2 = parseDate(d2);
    // ...
    // Your code continues   
}
于 2014-09-30T08:57:39.620 回答
1

我希望我可以让它更简单......但这似乎有效。

var d1 = '2014-10-09 08:10:58',
    d2 ='2015-10-09 08:10:50';

function getDateFromString(str) {
    var regexDate = /([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})/,
    values = regexDate.exec(str);
    return new Date(values[1], values[2], values[3], values[4], values[5], values[6]);
}
function daysInMonth(month,year) {
    return new Date(year, month, 0).getDate();
}

function dateDiff(d1,d2){
    if (d1.getTime() > d2.getTime()) {
        var oldD1 = d1;
        d1 = d2;
        d2 = oldD1;
    }
  var yearDiff = d2.getFullYear() - d1.getFullYear(),
      monthDiff = d2.getMonth() - d1.getMonth(),
      dayDiff = d2.getDate() - d1.getDate(),
      hourDiff = d2.getHours() - d1.getHours(),
      minDiff = d2.getMinutes() - d1.getMinutes(),
      secDiff = d2.getSeconds() - d1.getSeconds();

    if (secDiff < 0) {
        secDiff = 60 + secDiff;
        minDiff--;
    }
    if (minDiff < 0) {
        minDiff = 60 + minDiff;
        hourDiff--;
    }
    if (hourDiff < 0) {
        hourDiff = 24 + hourDiff;
        dayDiff--;
    }
    if (dayDiff < 0) {
        var days = daysInMonth(date2.getMonth(), date2.getFullYear());
        dayDiff = days + dayDiff;
        monthDiff--;
    }
    if (monthDiff < 0) {
        monthDiff = 12 + monthDiff;
        yearDiff--;
    }

  var diff = yearDiff > 0 ? yearDiff + " years " : "";
  diff += monthDiff > 0 ? monthDiff + " months " : "";
  diff += dayDiff > 0 ? dayDiff + " days " : "";
  diff += hourDiff > 0 ? hourDiff + " hours " : "";
  diff += minDiff > 0 ? minDiff + " minutes " : "";
  diff += secDiff > 0 ? secDiff + " seconds " : "";
  return diff;

}

var date1 = getDateFromString(d1),
    date2 = getDateFromString(d2)

document.getElementById('test').innerHTML += date1 + "<br />" + date2;

document.getElementById('test').innerHTML += "<br />" + dateDiff(date1, date2);

console.log(dateDiff(date1, date2));

JSFiddle

于 2014-09-30T09:45:50.590 回答
0

我假设您想要两个日期之间的差异。

var dateDiff  = function(d1/*String*/, d2/*String*/){
      var date1 = new Date(d1);
      var date2 = new Date(d2);
      var result = {
          negative:false
      };
      var diff = date1-date2;
      if(diff<0){
        result.negative = true;
        diff*=-1;
      }

      result.milliseconds = diff%1000;
      diff-=result.milliseconds;
      diff/=1000;

      result.seconds = diff%60;
      diff-=result.seconds
      diff/=60;

      result.minutes = diff%60;
      diff-=result.minutes
      diff/=60;

      result.hours = diff%24;
      diff-=result.hours

      result.days= diff/=24;
      //And so on
      return result;
}
于 2014-09-30T08:55:35.320 回答
0

它适用于所有浏览器。试试这个->

    d1 = '2014-10-09 08:10:56';
    d2 = '2014-11-09 10:10:56';
    var diff = dateDiff(d1,d2); 
    alert(diff);

    function splitDate(d1){
      var dSplit = d1.split(' ');	
      d = dSplit[0] + 'T' + dSplit[1];
      return d;
    }

    function dateDiff(d1,d2){
      d1 = splitDate(d1);
      d2 = splitDate(d2);
      var date1 = new Date(d1);
      var date2 = new Date(d2);
      var dateDiff = new Date(date2 - date1);    
      var diff = "Month " + dateDiff.getMonth() + ", Days " + dateDiff.getDay() + ", Hours " + dateDiff.getHours();
      return diff;

    }

于 2014-09-30T09:02:33.853 回答
0

我不确定我是否真的理解,但我认为这就是你想要的:http: //jsfiddle.net/OxyDesign/927n0L34/

JS

var difference = toDaysAndHours('2014-10-09 08:10:56','2014-11-09 10:10:56');

function toDaysAndHours(d1,d2){
    var dif, hours, days, difString = '';
    d1 = new Date(d1);
    d2 = new Date(d2);
    dif = Math.abs(d1 - d2);
    hours = (dif/(1000*60*60)).toFixed(0);
    days = (hours/24).toFixed(0);
    hours = hours - days*24;
    difString = days+' days, '+hours+' hours';
    return difString;
}
于 2014-09-30T09:39:36.450 回答
0

在第一个函数中,您使用的是字符串而不是日期。要正确初始化日期,请使用构造函数,如下所示:

d1 = new Date('2014-10-09 08:10:56')
d2 = new Date('2014-11-09 10:10:56')

然后在 d1 和 d2 上,您可以使用此处指定的所有 get*/set* 方法:http: //www.w3schools.com/jsref/jsref_obj_date.asp

虽然我在写答案时分心,但我看到其他人也说过类似的话,但我会补充一下:

数据对象方法有助于理解事物,但如果您想节省时间,请使用http://momentjs.com/或类似的模块来节省时间和错误。

于 2014-09-30T10:36:18.617 回答