Differenza date in JavaScript
Questa funzione permette di eseguire una differenza tra due date JavaScript e ritornare un oggetto con la differenza espressa in: giorni, ore, minuti e secondi:
ritorna un oggetto tipo:
che posso formattare con:
che ritorna:
Esempio:
JavaScript
var sgart = sgart || {};
sgart.date = sgart.date || {};
sgart.date.diff = function (dt1, dt2) {
const cSeconds = 1000, cMinutes = cSeconds * 60, cHours = cMinutes * 60, cDays = cHours * 24;
const diff = dt1 -dt2;
const df = diff / cDays, d = parseInt(df), dDiff = parseInt((df - d) * cDays);
const hf = dDiff / cHours, h = parseInt(hf), hDiff = parseInt((hf - h) * cHours);
const mf = hDiff / cMinutes, m = parseInt(mf), mDiff = parseInt((mf - m) * cMinutes);
const sf = mDiff / cSeconds, s = parseInt(sf), sDiff = parseInt((sf - s) * cSeconds);
return { d: d, h: h, m: m, s: s };
};
sgart.date.diff(new Date(), new Date(2017, 07, 5, 8, 24, 10));
JavaScript
{"d":32,"h":3,"m":45,"s":30}
JavaScript
sgart.date.diffString = function (dt1, dt2) {
const r= sgart.date.diff(dt1, dt2);
return r.d + 'd ' + r.h + 'h ' + r.m + 'm ' + r.s + 's';
};
sgart.date.diffString(new Date(), new Date(2017, 07, 5, 8, 24, 10));
JavaScript
32d 3h 45m 30s
Data di riferimento:
Risultato:
Oggetto JSON: