Javascript date format like ISO but local

A bit of a hack but can be done in one line by taking advantage of the fact that Sweden uses a format very close to ISO:

// Returns a string like 2021-01-17T01:59:57
function dateToISOButLocal(date) {
    return date.toLocaleString('sv').replace(' ', 'T');
}

To support milliseconds:

return date.toLocaleString('sv', {year:'numeric', month:'numeric', day:'numeric', hour:'numeric', minute:'numeric', second:'numeric', fractionalSecondDigits: 3}).replace(',', '.').replace(' ', 'T');

No library required! For some Date object, e.g. t = new Date()

  • convert the local time zone offset from minutes to milliseconds

    z = t.getTimezoneOffset() * 60 * 1000

  • subtract the offset from t

    tLocal = t-z

  • create shifted Date object

    tLocal = new Date(tLocal)

  • convert to ISO format string

    iso = tLocal.toISOString()

  • drop the milliseconds and zone

    iso = iso.slice(0, 19)

  • replace the ugly 'T' with a space

    iso = iso.replace('T', ' ')

Result is a nice ISO-ish format date-time string like "2018-08-01 22:45:50" in the local time zone.


I went with what Denis Howe said, below as a ready made function for convenience.

Also one fix: in the original answer t-z does not work because t is a Date, not milliseconds.

function dateToISOLikeButLocal(date) {
    const offsetMs = date.getTimezoneOffset() * 60 * 1000;
    const msLocal =  date.getTime() - offsetMs;
    const dateLocal = new Date(msLocal);
    const iso = dateLocal.toISOString();
    const isoLocal = iso.slice(0, 19);
    return isoLocal;
}

With this I get the kind of string that needed as a URL parameter:

"2018-11-16T12:23:50"

Tags:

Javascript