I want to convert time in milisecond to my local time in ISO format.
let time = 1668268800000
console.log(new Date(time).toISOString())
However this do not output my ISO date in my local time.
I want to convert time in milisecond to my local time in ISO format.
let time = 1668268800000
console.log(new Date(time).toISOString())
However this do not output my ISO date in my local time.
ISO is UTC by definition. Consider using JS's internationalization library to get dates in local format.
You can also do the conversion yourself:
let time = 1668268800000
let utcDate = new Date(time)
localTime = time - utcDate.getTimezoneOffset() * 60 * 1000
localDate = new Date(localTime)
localIso = localDate.toISOString()
console.log(utcDate.toISOString(), localIso)
That's correct.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
The timezone is always zero UTC offset, as denoted by the suffix Z.
You can create an ISO time string using the Date functions: Date.getFullYear()
, Date.getMonth()
, Date.getDate()
etc.
Once we have each of these values, we can combine to create the desired ISO string, adding the UTC offset in the format [+-]HH:MM.
This date will be formatted using the local timezone of the client.
function formatUTCOffset(minutes) {
return (minutes >= 0 ? '+': '-') + (Math.floor(Math.abs(minutes) / 60) + '').padStart(2, '0') + ':' + (Math.abs(minutes) % 60 + '').padStart(2, '0');
}
function formatDateElements(separator, ...elements) {
return elements.map(x => (x + '').padStart(2, '0')).join(separator);
}
function formatLocalISO(date) {
let isoDate = formatDateElements('-', date.getFullYear(), date.getMonth() + 1, date.getDate());
isoDate += 'T' + formatDateElements(':', date.getHours(), date.getMinutes(), date.getSeconds());
return isoDate + formatUTCOffset(-date.getTimezoneOffset());
}
let time = 1668268800000
console.log('ISO (1668268800000):', formatLocalISO(new Date(time)))
console.log('ISO (now): ', formatLocalISO(new Date()))
.as-console-wrapper { max-height: 100% !important; }