Skip to content Skip to sidebar Skip to footer

Get Date String From Utc Unixtime And Add A Timezone Offset

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'. F

Solution 1:

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))

Post a Comment for "Get Date String From Utc Unixtime And Add A Timezone Offset"