Using Date.js already, but can also use another library if necessary.
Not sure what is the best way to work with time deltas. Specifically, I want to display the time that has elapsed between now and a past date-time.
So I need to do something like this:
var elapsed_time = new Date() - pastDate;
pastDate.toString('days-hours-minutes-seconds');
Gotten it to mostly work using Date.js, but the problem is now I'm working with a Date object and not a timespan, so what should be an 23 hour time span is instead 23 hours after the Date's very first time:
var result = (new Date()) - past_date; "result" is the number (probably milliseconds): 15452732
var result = (new Date() - past_date "result" is a date from 1969: Wed Dec 31 1969 23:17:32
What I need is:
0 days 23 hours 17 minutes and 32 seconds
Any ideas?
The date and time is broken up and printed in a way that we can understand as humans. JavaScript, however, understands the date based on a timestamp derived from Unix time, which is a value consisting of the number of milliseconds that have passed since midnight on January 1st, 1970.
now() method is used to return the number of milliseconds elapsed since January 1, 1970, 00:00:00 UTC. Since now() is a static method of Date, it will always be used as Date.
Sounds like you need moment.js
e.g.
moment().subtract('days', 6).calendar();
=> last Sunday at 8:23 PM
moment().startOf('hour').fromNow();
=> 26 minutes ago
Edit:
Pure JS date diff calculation:
var date1 = new Date("7/Nov/2012 20:30:00");
var date2 = new Date("20/Nov/2012 19:15:00");
var diff = date2.getTime() - date1.getTime();
var days = Math.floor(diff / (1000 * 60 * 60 * 24));
diff -= days * (1000 * 60 * 60 * 24);
var hours = Math.floor(diff / (1000 * 60 * 60));
diff -= hours * (1000 * 60 * 60);
var mins = Math.floor(diff / (1000 * 60));
diff -= mins * (1000 * 60);
var seconds = Math.floor(diff / (1000));
diff -= seconds * (1000);
document.write(days + " days, " + hours + " hours, " + mins + " minutes, " + seconds + " seconds");
If you're not too worried in accuracy after days, you can simply do the maths
function timeSince(when) { // this ignores months
var obj = {};
obj._milliseconds = (new Date()).valueOf() - when.valueOf();
obj.milliseconds = obj._milliseconds % 1000;
obj._seconds = (obj._milliseconds - obj.milliseconds) / 1000;
obj.seconds = obj._seconds % 60;
obj._minutes = (obj._seconds - obj.seconds) / 60;
obj.minutes = obj._minutes % 60;
obj._hours = (obj._minutes - obj.minutes) / 60;
obj.hours = obj._hours % 24;
obj._days = (obj._hours - obj.hours) / 24;
obj.days = obj._days % 365;
// finally
obj.years = (obj._days - obj.days) / 365;
return obj;
}
then timeSince(pastDate);
and use the properties as you like.
Otherwise you can use .getUTC*
to calculate it, but note it may be slightly slower to calculate
function timeSince(then) {
var now = new Date(), obj = {};
obj.milliseconds = now.getUTCMilliseconds() - then.getUTCMilliseconds();
obj.seconds = now.getUTCSeconds() - then.getUTCSeconds();
obj.minutes = now.getUTCMinutes() - then.getUTCMinutes();
obj.hours = now.getUTCHours() - then.getUTCHours();
obj.days = now.getUTCDate() - then.getUTCDate();
obj.months = now.getUTCMonth() - then.getUTCMonth();
obj.years = now.getUTCFullYear() - then.getUTCFullYear();
// fix negatives
if (obj.milliseconds < 0) --obj.seconds, obj.milliseconds = (obj.milliseconds + 1000) % 1000;
if (obj.seconds < 0) --obj.minutes, obj.seconds = (obj.seconds + 60) % 60;
if (obj.minutes < 0) --obj.hours, obj.minutes = (obj.minutes + 60) % 60;
if (obj.hours < 0) --obj.days, obj.hours = (obj.hours + 24) % 24;
if (obj.days < 0) { // months have different lengths
--obj.months;
now.setUTCMonth(now.getUTCMonth() + 1);
now.setUTCDate(0);
obj.days = (obj.days + now.getUTCDate()) % now.getUTCDate();
}
if (obj.months < 0) --obj.years, obj.months = (obj.months + 12) % 12;
return obj;
}
a simple timestamp formatter in pure JS with custom patterns support and locale-aware, using Intl.RelativeTimeFormat
some formatting examples
/** delta: 1234567890, @locale: 'en-US', @style: 'long' */
/* D~ h~ m~ s~ */
14 days 6 hours 56 minutes 7 seconds
/* D~ h~ m~ s~ f~ */
14 days 6 hours 56 minutes 7 seconds 890
/* D#"d" h#"h" m#"m" s#"s" f#"ms" */
14d 6h 56m 7s 890ms
/* D,h:m:s.f */
14,06:56:07.890
/* D~, h:m:s.f */
14 days, 06:56:07.890
/* h~ m~ s~ */
342 hours 56 minutes 7 seconds
/* s~ m~ h~ D~ */
7 seconds 56 minutes 6 hours 14 days
/* up D~, h:m */
up 14 days, 06:56
the code & test
/**
Init locale formatter:
timespan.locale(@locale, @style)
Example:
timespan.locale('en-US', 'long');
timespan.locale('es', 'narrow');
Format time delta:
timespan.format(@pattern, @milliseconds)
@pattern tokens:
D: days, h: hours, m: minutes, s: seconds, f: millis
@pattern token extension:
h => '0'-padded value,
h# => raw value,
h~ => locale formatted value
Example:
timespan.format('D~ h~ m~ s~ f "millis"', 1234567890);
output: 14 days 6 hours 56 minutes 7 seconds 890 millis
NOTES:
* milliseconds unit have no locale translation
* may encounter declension issues for some locales
* use quoted text for raw inserts
*/
const timespan = (() => {
let rtf, tokensRtf;
const
tokens = /[Dhmsf][#~]?|"[^"]*"|'[^']*'/g,
map = [
{t: [['D', 1], ['D#'], ['D~', 'day']], u: 86400000},
{t: [['h', 2], ['h#'], ['h~', 'hour']], u: 3600000},
{t: [['m', 2], ['m#'], ['m~', 'minute']], u: 60000},
{t: [['s', 2], ['s#'], ['s~', 'second']], u: 1000},
{t: [['f', 3], ['f#'], ['f~']], u: 1}
],
locale = (value, style = 'long') => {
try {
rtf = new Intl.RelativeTimeFormat(value, {style});
} catch (e) {
if (rtf) throw e;
return;
}
const h = rtf.format(1, 'hour').split(' ');
tokensRtf = new Set(rtf.format(1, 'day').split(' ')
.filter(t => t != 1 && h.indexOf(t) > -1));
return true;
},
fallback = (t, u) => u + ' ' + t.fmt + (u == 1 ? '' : 's'),
mapper = {
number: (t, u) => (u + '').padStart(t.fmt, '0'),
string: (t, u) => rtf ? rtf.format(u, t.fmt).split(' ')
.filter(t => !tokensRtf.has(t)).join(' ')
.trim().replace(/[+-]/g, '') : fallback(t, u),
},
replace = (out, t) => out[t] || t.slice(1, t.length - 1),
format = (pattern, value) => {
if (typeof pattern !== 'string')
throw Error('invalid pattern');
if (!Number.isFinite(value))
throw Error('invalid value');
if (!pattern)
return '';
const out = {};
value = Math.abs(value);
pattern.match(tokens)?.forEach(t => out[t] = null);
map.forEach(m => {
let u = null;
m.t.forEach(t => {
if (out[t.token] !== null)
return;
if (u === null) {
u = Math.floor(value / m.u);
value %= m.u;
}
out[t.token] = '' + (t.fn ? t.fn(t, u) : u);
})
});
return pattern.replace(tokens, replace.bind(null, out));
};
map.forEach(m => m.t = m.t.map(t => ({
token: t[0], fmt: t[1], fn: mapper[typeof t[1]]
})));
locale('en');
return {format, locale};
})();
/************************** test below *************************/
const
cfg = {
locale: 'en,de,nl,fr,it,es,pt,ro,ru,ja,kor,zh,th,hi',
style: 'long,narrow'
},
el = id => document.getElementById(id),
locale = el('locale'), loc = el('loc'), style = el('style'),
fd = new Date(), td = el('td'), fmt = el('fmt'),
run = el('run'), out = el('out'),
test = () => {
try {
const tv = new Date(td.value);
if (isNaN(tv)) throw Error('invalid "datetime2" value');
timespan.locale(loc.value || locale.value, style.value);
const delta = fd.getTime() - tv.getTime();
out.innerHTML = timespan.format(fmt.value, delta);
} catch (e) { out.innerHTML = e.message; }
};
el('fd').innerText = el('td').value = fd.toISOString();
el('fmt').value = 'D~ h~ m~ s~ f~ "ms"';
for (const [id, value] of Object.entries(cfg)) {
const elm = el(id);
value.split(',').forEach(i => elm.innerHTML += `<option>${i}</option>`);
}
i {color:green}
locale: <select id="locale"></select>
custom: <input id="loc" style="width:8em"><br>
style: <select id="style"></select><br>
datetime1: <i id="fd"></i><br>
datetime2: <input id="td"><br>
pattern: <input id="fmt">
<button id="run" onclick="test()">test</button><br><br>
<i id="out"></i>
You can use momentjs duration object
Example:
const diff = moment.duration(Date.now() - new Date(2010, 1, 1))
console.log(`${diff.years()} years ${diff.months()} months ${diff.days()} days ${diff.hours()} hours ${diff.minutes()} minutes and ${diff.seconds()} seconds`)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With