Tom
Tom

Reputation: 2661

How to get a date object from a different timezone in utc format in js

I am located in the PDT timezone. When I type in new Date() into the browser's console, I get Tue Aug 31 2021 09:43:15 GMT-0700 (Pacific Daylight Time).

Now, I want the date in the same format from the central time region.

So I want the time object to look like this: Aug 31 2021 11:43:15 GMT-0500 (Central Daylight Time)

I've been reading the docs about Intl, Intl.DateTimeFormat() and toLocalTimeString() but can't seem to find it.

I tried new Date().toLocaleString(undefined, { timeZone: "US/Central" }) which gives me "8/31/2021, 11:46:30 AM", which is correct but not the right format.

I tried new Intl.DateTimeFormat('en-US', { dateStyle: 'full', timeStyle: 'long', timeZone:"US/Central" }).format(new Date()) which also gives me a string and not a date object in UTC format.

What am I doing wrong?

Upvotes: 3

Views: 232

Answers (1)

Jürgen Fink
Jürgen Fink

Reputation: 3545

Date in JS is a tricky issue - I agree 100% with you:

I did it once the hard way:

  1. splitting the resulting date object into parts
  2. concat all the parts according to my desired custom format

Maybe not the most elegant way, but it worked. Any suggestions from other contributors are very welcome.

Edit:
Added let oTZPartsReduced = ... in reply to valuable comment from @RobG

let myTimeZone = new Date();
console.log(myTimeZone);
//console.log((myTimeZone.getTimezoneOffset()/60).toFixed(2));

// oTZ = otherTimeZone  (to keep it short)
let oTZ = new Date(myTimeZone).toLocaleString("en-US", {timeZone: "US/Central"});

let oTZFormatted;

let oTZParts = new Intl.DateTimeFormat('en', {
  weekday: 'short',
  day:'2-digit',
  month: 'short',
  year: 'numeric',
  hour: '2-digit',
  minute: '2-digit',
  second: '2-digit',
  timeZone: 'US/Central' // <-- here it goes, your wished timeZone
}).formatToParts(new Date(myTimeZone));

oTZFormatted = oTZParts[2].value + ' ' + oTZParts[4].value + ' '+ oTZParts[6].value + ' '+ oTZParts[8].value + ':'+ oTZParts[10].value + ':'+ oTZParts[12].value + ' GMT-0500 (Central Daylight Time)';

// order within above array could vary due to language as @RobG stated - thanks
// hence following reduced version of above array:
let oTZPartsReduced = oTZParts.reduce((acc, part) => {
  if (part.type != 'literal') {
    acc[part.type] = part.value;
  }
  return acc;
}, Object.create(null));

oTZFormatted = oTZPartsReduced.month + ' ' + oTZPartsReduced.day + ' '+ oTZPartsReduced.year + ' '+ oTZPartsReduced.hour + ':'+ oTZPartsReduced.minute + ':'+ oTZPartsReduced.second + ' GMT-0500 (Central Daylight Time)';

console.log(oTZFormatted);
console.log('Array of Parts for reference:');
console.log(oTZParts);
console.log('Object (reduced) of Parts for reference:');
console.log(oTZPartsReduced);

Upvotes: 3

Related Questions