I'm building a personal blog using GitHub Pages and a desktop app with NWJS to do the back end administration however I have a big question when presenting dates on the front end.
Because this is a "static" site, the posts are markdown
files and their configuration files json
, in the desktop application use moment .js to save the timestamp of the publication (or edition) but I do not know the best approach (or method) to deal with the user's timezone since the javascript
function is responsible for showing how much time has been spent the publication (edit) depends on the user's timezone.
When making a publication the timestamp is based on my computer's time (or custom setting moment.js) bad users from a different timezone received different times on the front end based on their own times.
I'm not sure how to proceed to resolve this? Thanks for any help or referral links.
function.js
/**
* Time ago (UNIX)
* @param {string|number} time
* @return {string} human readable time elapsed
*/
function timeAgo(time){
var round = Math.round,
now = new Date,
t;
//
let format = function(n, unit){
let a = 'hour' == unit ? 'an' : '1';
unit = 1 == n ? unit : (unit !== 'month' ? unit + 's' : unit);
return (1 == n ? a : n) + ' ' + unit;
};
// past / future
let diff = (time > now) ? (time - now) : (now - time);
// just now
if (1e3 > diff) return 'now';
// s, m, h, d, w, m, y
if (60 > (t = round(diff / 1e3))) return format(t, 'second');
if (60 > (t = round(diff / 6e4))) return format(t, 'minute');
if (24 > (t = round(diff / 3.6e+6))) return format(t, 'hour');
if (7 > (t = round(diff / 8.64e+7))) return format(t, 'day');
if (4.34812 > (t = diff / 6.048e+8)) return format(round(t), 'week');
if (12 > (t = round(diff / 2.63e+9))) return format(t, 'month');
if (10 > (t = round(diff / 3.156e+10))) return format(t, 'year');
// decades
return format(round(diff / 3.156e+11), 'decade');
};
let btn = document.getElementById('click');
btn.addEventListener('click', function(ev){
ev.preventDefault();
let now = timeAgo(1502085380495);
let span = document.getElementById('show');
span.innerHTML = 'Published there ' + now;
}, false);
<button id="click">click to example</button>
<br>
<br>
<span id="show"></span>