Come trovare la differenza tra due date?Differenza tra le date in JavaScript
risposta
Utilizzando il valore Date oggetto ei suoi millisecondi, le differenze possono essere calcolate:
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.
Si può ottenere il numero di secondi (come numero intero/numero intero) dividendo i millisecondi da 1000 a convertirlo a secondi poi convertire il risultato a un numero intero (questo elimina la parte frazionaria rappresenta i millisecondi):
var seconds = parseInt((b-a)/1000);
È quindi possibile ottenere tutta minutes
dividendo seconds
del 60 e convertendolo in un numero intero, quindi hours
dividendo minutes
per 60 e convertendolo in un numero intero, quindi unità di tempo più lunghe nello stesso modo. Da questo, una funzione per ottenere l'intera quantità massima di un'unità di tempo nel valore di un'unità inferiore e la parte 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 il secondo Date object 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.
Non è necessario chiamare il costruttore 'Date' con tutti gli argomenti, è possibile chiamarlo solo con Anno e Mese, gli altri argomenti sono facoltativi. – CMS
Grazie, CMS. Volevo essere sicuro che l'utente capisse che potevano diventare molto granulari con le loro specifiche. – Sampson
Ho aggiornato la soluzione per comunicare il tuo punto, CMS. Apprezzo l'heads-up. – Sampson
// 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');
}
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ì semplice perché non puoi semplicemente aggiungere gli oggetti Data insieme. Per poter utilizzare un oggetto Date in qualsiasi tipo di calcolo, dobbiamo prima recuperare il valore interno del millisecondo della Data, che è memorizzato come un numero intero di grandi dimensioni. La funzione per farlo è Date.getTime(). Dopo che entrambe le date sono state convertite, la sottrazione di quella successiva a quella precedente restituisce la differenza in millisecondi. L'intervallo desiderato può quindi essere determinato dividendo quel numero per il corrispondente numero 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' l'arrotondamento è facoltativo, a seconda che si desideri o meno giorni parziali.
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);
}
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à gli anni bisestili (29 febbraio) e le differenze di lunghezza del mese in un modo che faremmo naturalmente (credo).
Quindi, ad esempio, l'intervallo tra il 28 febbraio 2015 e il 28 marzo 2015 sarà considerato esattamente un mese, non 28 giorni. Se entrambi questi giorni sono nel 2016, la differenza sarà comunque esattamente di un mese, non di 29 giorni.
Le date con esattamente lo stesso mese e giorno, ma 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 del conteggio di 365 giorni come 1 anno).
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;
}
utilizzo
var qtMonths = DateDiff ('mm', nuova data ('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());
O
var qtMonths = DateDiff ('m', nuova data ('2015/05/05'), new Date()); // m || y || d
var qtMonths = DateDiff ('month', new Date ('2015-05-05'), new Date()); // mese || anno || giorno
var qtMonths = DateDiff ('months', 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;
}
Eventuali duplicati di [confrontare due date con JavaScript] (https://stackoverflow.com/questions/492994/compare-two-dates-with-javascript) –