-1

I have api which will give a date and timezone

{"time":"2021-01-01 10:10:10","zone":"America/Denver"}

we are not sure which timezone they are providing

How to 1)convert time to local timezone 2)convert time to another timezone

i tried

date.toLocaleString("en-US", {timeZone: "any timezone"});

but this will consider date as your local timezone only

user
  • 29
  • 2
  • it does not work like that. all times and dates are in universal time. there is no time zone conversion, but just a display according to the time zone of your choice, or by default of the host system – Mister Jojo Apr 23 '22 at 18:21
  • it's better to ask them to provide the date in UTC or ISO format. – Danial Dezfouli Apr 23 '22 at 18:23
  • Does this answer your question? [Convert date to another timezone in JavaScript](https://stackoverflow.com/questions/10087819/convert-date-to-another-timezone-in-javascript) – Yogi Apr 23 '22 at 18:41

2 Answers2

0

you can use moment js for converting zone

var jun = moment("2014-06-01T12:00:00Z");
var dec = moment("2014-12-01T12:00:00Z");

jun.tz('America/Los_Angeles').format('ha z');  // 5am PDT
dec.tz('America/Los_Angeles').format('ha z');  // 4am PST

jun.tz('America/New_York').format('ha z');     // 8am EDT
dec.tz('America/New_York').format('ha z');     // 7am EST

jun.tz('Asia/Tokyo').format('ha z');           // 9pm JST
dec.tz('Asia/Tokyo').format('ha z');           // 9pm JST

jun.tz('Australia/Sydney').format('ha z');     // 10pm EST
dec.tz('Australia/Sydney').format('ha z');     // 11pm EST
0

To convert a date to another time zone, use the toLocaleString method

const date = new Date();

console.log(
  date.toLocaleString('en-US', {
    timeZone: 'America/New_York',
    dateStyle: 'full',
    timeStyle: 'full',
  }),
);

// result

"Sunday, April 24, 2022 at 4:42:40 AM Eastern Standard Time"