2

How to convert Javascript Date Object to another timezone but the result must be Date object with the correct timezone

let date = new Date();
console.log(date);

date = date.toLocaleString('en-US', { timeZone: 'America/Vancouver' });
date = new Date(date);
console.log(date);

that gives the following result, the last result line (Date/Time) is correct but the time zone is incorrect which is still GMT-0500 (Colombia Standard Time) but must be GMT-0800 (Pacific Standard Time) timezone

Wed Jan 20 2021 00:14:11 GMT-0500 (Colombia Standard Time)
Tue Jan 19 2021 21:14:11 GMT-0500 (Colombia Standard Time)
TropicsCold
  • 115
  • 6
Cloud-Lover
  • 304
  • 4
  • 12
  • Does this answer your question? [How to initialize a JavaScript Date to a particular time zone](https://stackoverflow.com/questions/15141762/how-to-initialize-a-javascript-date-to-a-particular-time-zone) – Lin Du Jan 20 '21 at 05:36
  • are you trying to display time with your local timezone? – Md Somir Jan 20 '21 at 05:41
  • You should consider using a library like `moment-timezone`. Makes working with dates/times and timezone one heck of a lot easier. – codemonkey Jan 20 '21 at 06:51

1 Answers1

2

You may try this :

    let date = new Date();
    console.log(date);
    date = date.toLocaleString("en-CA", {
      timeZone: "America/Vancouver",
      timeZoneName: "long",
    });
    console.log(date);

Output:

Wed Jan 20 2021 09:18:16 GMT+0300 (Arabian Standard Time)

2021-01-19, 10:18:16 p.m. Pacific Standard Time

Once you get the correct TimeZone, you may change how the date and time are displayed by string manipulation if you need too.

Update:

This may not look pretty but i believe it should satisfy the requirements:

    let date = new Date().toLocaleString("en-US", {
    timeZone: "America/Vancouver",
    timeZoneName: "short",
    });

    let date1 = new Date(date);
    //adding a new property to Date object called tz and initializing it to null
    Date.prototype.tz = null;
    //stting the tz value to the Time zone output from toLocalString
    date1.tz = date.slice(date.length - 3);
    
    console.log(date1.toISOString() + " " + date1.tz);
    console.log(date);
    console.log(typeof date1); 

Output:

2021-01-20T09:01:06.000Z PST

1/20/2021, 1:01:06 AM PST

Object

What i've done is create a new property of the object date to replace the built-in time zone property in Date, hence you get an object with a user specified Time zone.