简体   繁体   中英

How to convert a date to ISO format but with timezone info in place of the 'Z' in Javascript?

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

parser.isoparse('2019-08-28T14:34:25.518993Z') 使用它来获得正确的格式

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM