I would like to generate in JS a Date object (or XDate) starting from a UTC unix timestamp, add a timezone offset and then generate a String in the format "yyyy-MM-dd HH:mm:ss".
For now I did this:
createServerRelativeTs : function(unixtimeutc, utcoffset) {
var stimeUTCoffset = (isNaN(utcoffset)) ? 1 : utcoffset;
var time = new XDate(Math.round(unixtimeutc * 1000));
var hours = time.getUTCHours() + stimeUTCoffset;
time.setUTCHours(hours);
return time.toString("yyyy-MM-dd HH:mm:ss");
}
in which utcoffset is a integer number and unixtimeutc is a unixtimestamp
The problem with this code is that If I change the timezone in my OS the result changes! If I add the offset value to the timestamp it gets ignored. How can I get a OS-timezone-independent result?
This is really a combination of a few answers. You need to work in UTC to avoid the effects of the host timezone which is considered when using non-UTC methods.
So create a Date from the UNIX time value, adjust the UTC minutes for the offset, then format the output string using UTC methods as local.
This might be a bit simpler with a library, but it's not really necessary.
/* Given a Date, return a string in //yyyy-MM-dd HH:mm:ss format
** @param {Date} d
** @returns {string}
*/
function formatISOLocal(d) {
function z(n){return (n<10?'0':'')+n}
if (isNaN(d)) return d.toString();
return d.getUTCFullYear() + '-' +
z(d.getUTCMonth() + 1) + '-' +
z(d.getUTCDate()) + ' ' +
z(d.getUTCHours()) + ':' +
z(d.getUTCMinutes()) + ':' +
z(d.getUTCSeconds()) ;
}
/* Adjust time value for provided timezone
** @param {Date} d - date object
** @param {string} tz - UTC offset as +/-HH:MM or +/-HHMM
** @returns {Date}
*/
function adjustForTimezone(d, tz) {
var sign = /^-/.test(tz)? -1 : 1;
var b = tz.match(/\d\d/g); // should do some validation here
var offset = (b[0]*60 + +b[1]) * sign;
d.setUTCMinutes(d.getUTCMinutes() + offset);
return d;
}
// Given a UNIX time value for 1 Jan 2017 00:00:00,
// Return a string for the equivalent time in
// UTC+10:00
// 2017-01-01T00:00:00Z seconds
var n = 1483228800;
// Create Date object (a single number value is treated as a UTC time value)
var d = new Date(n * 1000);
// Adjust to UTC+10:00
adjustForTimezone(d, '+10:00');
// Format as local string
console.log(formatISOLocal(d))