Domanda

Come trovare la differenza tra due date?

È stato utile?

Soluzione

Utilizzando l'oggetto rel="noreferrer"> Data

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.

È possibile ottenere il numero di secondi (come un intero / numero intero) dividendo i millisecondi per 1000 per convertirlo in secondi e poi convertire il risultato in un intero (questo rimuove la parte frazionaria rappresenta i millisecondi):

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

Si può quindi ottenere tutta minutes dividendo seconds 60 viene convertito in un numero intero, hours dividendo minutes 60 viene convertito in un numero intero, unità di tempo più lungo nello stesso modo. Da questo, una funzione per ottenere l'intera quantità massima di un'unità di tempo del valore di un'unità inferiore e la restante unità inferiore può essere creato:

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.

Se vi state chiedendo quali sono i parametri di input forniti sopra per la seconda Data oggetto sono, vedere i loro nomi qui sotto:

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

Come notato nei commenti di questa soluzione, non è necessariamente bisogno di fornire tutti questi valori a meno che siano necessarie per la data che si desidera rappresentare.

Altri suggerimenti

Ho trovato questo e funziona bene per me:

calcolando la differenza tra due date noti

Purtroppo, il calcolo di un intervallo di date, come giorni, settimane o mesi tra due date conosciute non è così facile, perché non si può semplicemente aggiungere oggetti Date insieme. Per poter utilizzare un oggetto Date in qualsiasi tipo di calcolo, dobbiamo prima recuperare valore millisecondo interna della data, che viene memorizzato come un grande numero intero. La funzione per farlo è Date.getTime (). Una volta che entrambe le date sono state convertite, sottraendo l'uno più tardi da quello precedente restituisce la differenza in millisecondi. L'intervallo desiderato può quindi essere determinata dividendo questo numero per il numero corrispondente di millisecondi. Ad esempio, per ottenere il numero di giorni per un dato numero di millisecondi, avremmo dividere per 86,4 milioni, il numero di millisecondi in un giorno (1000 x 60 secondi x 60 minuti x 24 ore):

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

L'arrotondamento è opzionale, a seconda se si desidera giorni parziali o meno.

Riferimento

    // 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');
    }

Se siete alla ricerca di una differenza espressa come una combinazione di anni, mesi e giorni, vorrei suggerire questa funzione:

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

Questa soluzione tratterà anni bisestili (29 febbraio) e differenze di lunghezza mese in un modo che sarebbe naturalmente fare (credo).

Così, per esempio, l'intervallo tra il 28 febbraio 2015 e 28 marzo 2015 sarà considerato un mese esatto, non 28 giorni. Se entrambi quei giorni sono nel 2016, la differenza sarà ancora esattamente un mese, non 29 giorni.

Date con esattamente lo stesso mese e giorno, ma l'anno diverso, avranno sempre una differenza di un numero esatto di anni. Quindi la differenza tra 2015/03/01 e 2016/03/01 sarà esattamente 1 anno, non 1 anno e 1 giorno (a causa della contando 365 giorni come 1 anno).

Questa risposta, sulla base di un altro (link alla fine), è circa la differenza tra due date.
Si può vedere come funziona perché è semplice, anche esso include dividere la differenza in
unità di tempo (una funzione che feci) e la conversione in UTC per fermare problemi di fuso orario.

function date_units_diff(a, b, unit_amounts) {
    var split_to_whole_units = function (milliseconds, unit_amounts) {
        // unit_amounts = list/array of amounts of milliseconds in a
        // second, seconds in a minute, etc., for example "[1000, 60]".
        time_data = [milliseconds];
        for (i = 0; i < unit_amounts.length; i++) {
            time_data.push(parseInt(time_data[i] / unit_amounts[i]));
            time_data[i] = time_data[i] % unit_amounts[i];
        }; return time_data.reverse();
    }; if (unit_amounts == undefined) {
        unit_amounts = [1000, 60, 60, 24];
    };
    var utc_a = new Date(a.toUTCString());
    var utc_b = new Date(b.toUTCString());
    var diff = (utc_b - utc_a);
    return split_to_whole_units(diff, unit_amounts);
}

// Example of use:
var d = date_units_diff(new Date(2010, 0, 1, 0, 0, 0, 0), new Date()).slice(0,-2);
document.write("In difference: 0 days, 1 hours, 2 minutes.".replace(
   /0|1|2/g, function (x) {return String( d[Number(x)] );} ));

Come il mio codice funziona sopra

A differenza di data / ora, come millisecondi, può essere calcolata utilizzando la Data oggetto:

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

var utc_a = new Date(a.toUTCString());
var utc_b = new Date(b.toUTCString());
var diff = (utc_b - utc_a); // The difference as milliseconds.

Quindi per calcolare il numero di secondi in questa differenza, dividerlo per 1000 per convertire
millisecondi a secondi, quindi modificare il risultato in un numero intero (numero intero) per rimuovere
i millisecondi (parte frazione di quella decimale):. var seconds = parseInt(diff/1000)
Inoltre, ho potuto ottenere unità di tempo più lunghi utilizzando lo stesso processo, per esempio:
 - (interi) minuti , che divide secondi di 60 e cambiando il risultato in un intero,
 -. ore , dividendo minuti di 60 e cambiando il risultato di un intero

ho creato una funzione per fare quel processo di dividere la differenza in
unità intere di tempo, di nome split_to_whole_units, con questo demo:

console.log(split_to_whole_units(72000, [1000, 60]));
// -> [1,12,0] # 1 (whole) minute, 12 seconds, 0 milliseconds.

Questa risposta si basa su quest'altro .

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 );
}
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;

}
  

Uso

     

var qtMonths = DateDiff ( 'mm', new Date ( '2015/05/05'), new Date ());

     

var qtYears = DateDiff ( 'aa', new Date ( '2015/05/05'), new Date ());

     

var qtDays = DateDiff ( 'dd', new Date ( '2015/05/05'), new Date ());

     
    

o

         

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

         

var qtMonths = DateDiff ( 'mese', new Date ( '2015/05/05'), new Date ()); // mese || anno || giorno

         

var qtMonths = DateDiff ( 'mesi, new Date ( '2015/05/05'), new Date ()); // mesi || anni || giorni

         

...

  
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;

}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top