Reputation: 421
Currently, I am converting the UTC time to a time of a specific timezone using Moment.js in my backend. It allows me to convert 2021-01-04T01:20:00Z
to 2021-01-03T20:20:00-05:00
for America/toronto
timezone.
I am wondering if I can achieve this conversion with JS without a module such as Moment.js?
Upvotes: 1
Views: 2986
Reputation: 179
Here's a solution that is very re-usable.
//Adds the toIsoString() function to the date object
Date.prototype.toIsoString = function() {
var tzo = -this.getTimezoneOffset(),
dif = tzo >= 0 ? '+' : '-',
pad = function(num) {
var norm = Math.floor(Math.abs(num));
return (norm < 10 ? '0' : '') + norm;
};
return this.getFullYear() +
'-' + pad(this.getMonth() + 1) +
'-' + pad(this.getDate()) +
'T' + pad(this.getHours()) +
':' + pad(this.getMinutes()) +
':' + pad(this.getSeconds()) +
dif + pad(tzo / 60) +
':' + pad(tzo % 60);
}
//Creates a date object with the utc supplied, which automatically gets translated to your timezone
var localISOTime = new Date('2021-01-04T01:20:00Z');
//Outputs the date in ISO format with the timezone extension
console.log(localISOTime.toIsoString());
Upvotes: 1
Reputation: 564
new Date('2021-01-04T01:20:00Z').toLocaleString('en-US', {timeZone: 'America/Toronto'})
"1/3/2021, 8:20:00 PM"
options = {
year: 'numeric', month: 'numeric', day: 'numeric',
hour: 'numeric', minute: 'numeric', second: 'numeric',
hour12: false,
timeZone: 'America/Toronto'
};
new Date('2021-01-04T01:20:00Z').toLocaleString('en-US', options)
or
new Intl.DateTimeFormat('en-US', options).format(new Date('2021-01-04T01:20:00Z'))
"1/3/2021, 20:20:00"
options = {
year: 'numeric', month: 'numeric', day: 'numeric',
hour: 'numeric', minute: 'numeric', second: 'numeric',
hour12: false,
timeZone: 'America/Toronto',
timeZoneName: 'short'
};
new Intl.DateTimeFormat('en-US', options).format(new Date('2021-01-04T01:20:00Z'))
"1/3/2021, 20:20:00 EST"
Upvotes: 2