It seems JS has until today no native (!) solution to get an ISO 8601 date & time string in the local time zone (it’s always in UTC). (Super weird, but okay).
I updated the solution on Stackoverflow a bit using “new” ES2017 functionality like this:
function getISOLocalString() {
let date = new Date();
let tzo = -date.getTimezoneOffset();
if (tzo === 0) {
return date.toISOString();
} else {
let dif = tzo >= 0 ? "+" : "-";
let pad = function (num, digits = 2) {
return String(num).padStart(digits, "0");
};
return (
date.getFullYear() +
"-" +
pad(date.getMonth() + 1) +
"-" +
pad(date.getDate()) +
"T" +
pad(date.getHours()) +
":" +
pad(date.getMinutes()) +
":" +
pad(date.getSeconds()) +
dif +
pad(tzo / 60) +
":" +
pad(tzo % 60) +
"." +
pad(date.getMilliseconds(), 3)
);
}
}
console.log(getISOLocalString());

Leave a Reply