0

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.

Aidenhsy
  • 915
  • 2
  • 13
  • 28
  • I think the definition of ISO is that it's always in UTC. You can manually subtract the timezone difference from the epoch to get what you want though. – sleepystar96 Nov 16 '22 at 03:33

3 Answers3

1

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)
sleepystar96
  • 721
  • 3
  • 12
  • Hi there, localIso is the same as utcDate.toISOString() – Aidenhsy Nov 16 '22 at 03:59
  • Nope, `localIso == utcDate.toISOString()` should yield false, unless your local timezone/system is set to UTC. Here are outputs for me: `utcDate.toISOString(): 2022-11-12T16:00:00.000Z, localIso: 2022-11-12T11:00:00.000Z`. There is a 5hr difference for me locally. – sleepystar96 Nov 16 '22 at 04:02
  • 1
    nvm there was something wrong with my browser. thank you so much! – Aidenhsy Nov 16 '22 at 04:07
  • 1
    no problem, be careful not to shoot yourself in the foot by calling the localIso "true ISO" though later on. – sleepystar96 Nov 16 '22 at 04:11
0

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.

ceejayoz
  • 176,543
  • 40
  • 303
  • 368
0

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; }
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40