1

I have always worked with dates in ISO format that ends with a 'Z'. But now I have to replace that 'Z' with timezone info like +08:00.

In other words, currently I have this format 2020-01-17T00:30:00.000Z, but now I need it in this format 2020-01-17T08:30:00+08:00.

Looks like popular date library like moment and dayjs convert date to ISO format without 'Z' too by default. Is that still considered an 'ISO' date format? And I can't find out how to do it with vanilla Javascript and doing the .toISOString() always gives me the 'Z'..

kyw
  • 6,685
  • 8
  • 47
  • 59

3 Answers3

0

parser.isoparse('2019-08-28T14:34:25.518993Z') use this to get correct format

Arun C S
  • 51
  • 2
0

The Z ("Zulu") on the end means UTC, ie. an offset from UTC of zero. I'm assuming you want to convert from UTC to local time, in which case you need to calculate the offset from UTC:

function convertUTCDateToLocalDate(date) {
    const newDate = new Date(date.getTime() + date.getTimezoneOffset() * 60 * 1000);
    const offset = date.getTimezoneOffset() / 60;
    const hours = date.getHours();

    newDate.setHours(hours - offset);

    return newDate;   
}

Usage:

const date = new Date("2020-01-17T00:30:00.000Z")
const newDate = convertUTCDateToLocalDate(date)
newDate.toISOString() // "2020-01-17T01:30:00.000+01:00"

Beware! This solution won't work for timezones where the offset isn't a full hour.

If you're running this in a browser I'd strongly recommend using a tool like moment.

AJ Hurst
  • 358
  • 4
  • 11
0

If you get the date string in the ISO format, but you want to get the string in a certain timezone, with the timezone.

Then here's a simple function that does just that.

function getISODateStampWithTZ (date, tzHours) 
{
    let dateTz = new Date(date);
    dateTz.setUTCHours(tzHours);
    return dateTz.toISOString().replace(/Z$/,
       (tzHours<0 ? '-' : '+') +
       (Math.abs(tzHours)<10 ? '0'+Math.abs(tzHours) : Math.abs(tzHours)) +
       ':00');
}

const date = new Date('2020-01-17T00:30:00.000Z');

console.log(date.toISOString());
console.log(getISODateStampWithTZ(date, 8));
console.log(getISODateStampWithTZ(date, -1));

Such function could also be added to the Date prototype.

The example below prefixes the function with 'custom' to make it distinct from standard methods.

Date.prototype.customToISOStringTZ = function  (tzHours) 
{
    let dateTz = new Date(this);
    dateTz.setUTCHours(tzHours);
    return dateTz.toISOString().replace(/Z$/,
       (tzHours<0 ? '-' : '+') +
       (Math.abs(tzHours)<10 ? '0'+Math.abs(tzHours) : Math.abs(tzHours)) +
       ':00');
}

const date = new Date('2020-01-17T00:30:00.000Z');

console.log(date.toISOString());
console.log(date.customToISOStringTZ(8));
console.log(date.customToISOStringTZ(-1));
LukStorms
  • 28,916
  • 5
  • 31
  • 45