Różnica między datami w JavaScript

Jak znaleźć różnicę między dwoma datami?

Author: S.L. Barth, 2009-12-28

6 answers

Za pomocą obiektu Date i jego wartości milisekund można obliczyć różnice:

var a = new Date(); // Current date now.
var b = new Date(2010, 0, 1, 0, 0, 0, 0); // Start of 2010.
var d = (b-a); // Difference in milliseconds.

Możesz uzyskać liczbę sekund (jako liczbę całkowitą/całkowitą) dzieląc milisekundy przez 1000, aby przekonwertować ją na sekundy, a następnie przekonwertować wynik na liczbę całkowitą (usuwa to część ułamkową reprezentującą milisekundy):

var seconds = parseInt((b-a)/1000);

Można następnie uzyskać całość minutes dzieląc seconds przez 60 i przekształcając ją na liczbę całkowitą, następnie hours dzieląc minutes przez 60 i konwersja go do liczby całkowitej, a następnie dłuższe jednostki czasu w ten sam sposób. Z tego można utworzyć funkcję, aby uzyskać maksymalną całkowitą ilość jednostki czasu w wartości niższej jednostki, a pozostałą dolną jednostkę:

function get_whole_values(base_value, time_fractions) {
    time_data = [base_value];
    for (i = 0; i < time_fractions.length; i++) {
        time_data.push(parseInt(time_data[i]/time_fractions[i]));
        time_data[i] = time_data[i] % time_fractions[i];
    }; return time_data;
};
// Input parameters below: base value of 72000 milliseconds, time fractions are
// 1000 (amount of milliseconds in a second) and 60 (amount of seconds in a minute). 
console.log(get_whole_values(72000, [1000, 60]));
// -> [0,12,1] # 0 whole milliseconds, 12 whole seconds, 1 whole minute.

Jeśli zastanawiasz się, jakie są parametry wejściowe dla drugiego obiektu Date , zobacz ich nazwy poniżej:

new Date(<year>, <month>, <day>, <hours>, <minutes>, <seconds>, <milliseconds>);

Jak wspomniano w komentarzach do tego rozwiązania, nie musisz koniecznie podawać wszystkich tych wartości, chyba że są niezbędne do daty, którą chcesz reprezentować.

 88
Author: Sampson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-03 16:34:57

Znalazłem to i działa dobrze dla mnie:

Obliczanie różnicy między dwoma znanymi datami

Niestety, obliczanie przedziału dat, takiego jak dni, tygodnie lub miesiące między dwiema znanymi datami, nie jest tak proste, ponieważ nie można po prostu dodawać obiektów daty razem. Aby użyć obiektu Date w jakimkolwiek obliczeniu, musimy najpierw pobrać wewnętrzną wartość milisekundy daty, która jest przechowywana jako duża liczba całkowita. Funkcją do tego jest data.getTime (). Po przekonwertowaniu obu dat, odejmowanie późniejszej od wcześniejszej zwraca różnicę w milisekundach. Żądany interwał można następnie określić dzieląc tę liczbę przez odpowiednią liczbę milisekund. Na przykład, aby uzyskać liczbę dni dla danej liczby milisekund, podzielimy przez 86,400,000, liczbę milisekund w ciągu dnia (1000 x 60 sekund x 60 minut x 24 godzin):

Date.daysBetween = function( date1, date2 ) {
  //Get 1 day in milliseconds
  var one_day=1000*60*60*24;

  // Convert both dates to milliseconds
  var date1_ms = date1.getTime();
  var date2_ms = date2.getTime();

  // Calculate the difference in milliseconds
  var difference_ms = date2_ms - date1_ms;

  // Convert back to days and return
  return Math.round(difference_ms/one_day); 
}

//Set the two dates
var y2k  = new Date(2000, 0, 1); 
var Jan1st2010 = new Date(y2k.getFullYear() + 10, y2k.getMonth(), y2k.getDate());
var today= new Date();
//displays 726
console.log( 'Days since ' 
           + Jan1st2010.toLocaleDateString() + ': ' 
           + Date.daysBetween(Jan1st2010, today));

Zaokrąglenie jest opcjonalne, w zależności od tego, czy chcesz częściowe dni, czy nie.

Odniesienie

 4
Author: Adrian P.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-23 13:12:11
    // This is for first date
    first = new Date(2010, 03, 08, 15, 30, 10); // Get the first date epoch object
    document.write((first.getTime())/1000); // get the actual epoch values
    second = new Date(2012, 03, 08, 15, 30, 10); // Get the first date epoch object
    document.write((second.getTime())/1000); // get the actual epoch values
    diff= second - first ;
    one_day_epoch = 24*60*60 ;  // calculating one epoch
    if ( diff/ one_day_epoch > 365 ) // check , is it exceei
    {
    alert( 'date is exceeding one year');
    }
 3
Author: Pavunkumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-03-08 10:31:03

Jeśli szukasz różnicy wyrażonej jako kombinacja lat, miesięcy i dni, proponuję tę funkcję:

function interval(date1, date2) {
    if (date1 > date2) { // swap
        var result = interval(date2, date1);
        result.years  = -result.years;
        result.months = -result.months;
        result.days   = -result.days;
        result.hours  = -result.hours;
        return result;
    }
    result = {
        years:  date2.getYear()  - date1.getYear(),
        months: date2.getMonth() - date1.getMonth(),
        days:   date2.getDate()  - date1.getDate(),
        hours:  date2.getHours() - date1.getHours()
    };
    if (result.hours < 0) {
        result.days--;
        result.hours += 24;
    }
    if (result.days < 0) {
        result.months--;
        // days = days left in date1's month, 
        //   plus days that have passed in date2's month
        var copy1 = new Date(date1.getTime());
        copy1.setDate(32);
        result.days = 32-date1.getDate()-copy1.getDate()+date2.getDate();
    }
    if (result.months < 0) {
        result.years--;
        result.months+=12;
    }
    return result;
}

// Be aware that the month argument is zero-based (January = 0)
var date1 = new Date(2015, 4-1, 6);
var date2 = new Date(2015, 5-1, 9);

document.write(JSON.stringify(interval(date1, date2)));

To rozwiązanie potraktuje lata przestępne (29 lutego) i różnice w długości miesięcy w sposób, który naturalnie byśmy zrobili (myślę).

Tak więc na przykład okres między 28 lutego 2015 r. a 28 marca 2015 r. będzie uważany za dokładnie jeden miesiąc, a nie 28 dni. Jeśli oba te dni są w 2016 roku, różnica nadal będzie dokładnie jedna miesiąc, Nie 29 dni.

Daty Z dokładnie tym samym miesiącem i dniem, ale innym rokiem, zawsze będą miały różnicę dokładnej liczby lat. Tak więc różnica między 2015-03-01 a 2016-03-01 będzie wynosić dokładnie 1 rok, a nie 1 rok i 1 dzień (ze względu na liczenie 365 dni jako 1 rok).

 1
Author: trincot,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-10 14:02:25
Date.prototype.addDays = function(days) {

   var dat = new Date(this.valueOf())
   dat.setDate(dat.getDate() + days);
   return dat;
}

function getDates(startDate, stopDate) {

  var dateArray = new Array();
  var currentDate = startDate;
  while (currentDate <= stopDate) {
    dateArray.push(currentDate);
    currentDate = currentDate.addDays(1);
  }
  return dateArray;
}

var dateArray = getDates(new Date(), (new Date().addDays(7)));

for (i = 0; i < dateArray.length; i ++ ) {
  //  alert (dateArray[i]);

    date=('0'+dateArray[i].getDate()).slice(-2);
    month=('0' +(dateArray[i].getMonth()+1)).slice(-2);
    year=dateArray[i].getFullYear();
    alert(date+"-"+month+"-"+year );
}
 0
Author: user3230982,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-01-10 04:01:59
var DateDiff = function(type, start, end) {

    let // or var
        years = end.getFullYear() - start.getFullYear(),
        monthsStart = start.getMonth(),
        monthsEnd = end.getMonth()
    ;

    var returns = -1;

    switch(type){
        case 'm': case 'mm': case 'month': case 'months':
            returns = ( ( ( years * 12 ) - ( 12 - monthsEnd ) ) + ( 12 - monthsStart ) );
            break;
        case 'y': case 'yy': case 'year': case 'years':
            returns = years;
            break;
        case 'd': case 'dd': case 'day': case 'days':
            returns = ( ( end - start ) / ( 1000 * 60 * 60 * 24 ) );
            break;
    }

    return returns;

}

Użycie

Var qtMonths = DateDiff ('mm', new Date ('2015-05-05'), new Date ());

Var qtYears = DateDiff ('yy', new Date ('2015-05-05'), new Date ());

Var qtDays = DateDiff ('dd', new Date ('2015-05-05'), new Date ());

Lub

Var qtMonths = DateDiff ('m', new Date ('2015-05-05'), new Date ()); / / m || y || d

Var qtMonths = DateDiff ('month', new Date ('2015-05-05'), new date ()); / / month / / rok / / Dzień

Var qtMonths = DateDiff ('months', new Date ('2015-05-05'), new Date ()); / / months || years || days

...

var DateDiff = function (type, start, end) {

    let // or var
        years = end.getFullYear() - start.getFullYear(),
        monthsStart = start.getMonth(),
        monthsEnd = end.getMonth()
    ;

    if(['m', 'mm', 'month', 'months'].includes(type)/*ES6*/)
        return ( ( ( years * 12 ) - ( 12 - monthsEnd ) ) + ( 12 - monthsStart ) );
    else if(['y', 'yy', 'year', 'years'].includes(type))
        return years;
    else if (['d', 'dd', 'day', 'days'].indexOf(type) !== -1/*EARLIER JAVASCRIPT VERSIONS*/)
        return ( ( end - start ) / ( 1000 * 60 * 60 * 24 ) );
    else
        return -1;

}
 0
Author: user3245067,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-06 18:37:52