convert pacific time to gmt in typescript

To convert Pacific Time (PT) to Greenwich Mean Time (GMT) in TypeScript, we can use the toLocaleString method on a Date object and pass in the desired time zone as an argument. Specifically, we can pass in "en-US" as the locale and then pass in options with the timeZone property set to "GMT".

Here is an example function that takes in a PT date string and returns the equivalent date and time in GMT:

index.ts
function convertPSTtoGMT(pstDateString: string): string {
  const pstDate = new Date(pstDateString);
  const gmtOptions = { timeZone: 'GMT' };
  const gmtDateString = pstDate.toLocaleString('en-US', gmtOptions);
  return gmtDateString;
}
238 chars
7 lines

We create a new Date object from the PT date string input. Then, we create a gmtOptions object with the desired time zone set to "GMT". Finally, we use the toLocaleString method to format the date as a string in the en-US locale with the gmtOptions applied.

Example usage of this function:

index.ts
const pstString = '2021-10-10T15:30:00-07:00';
const gmtString = convertPSTtoGMT(pstString);
console.log(gmtString); // Output: "10/10/2021, 22:30:00"
151 chars
4 lines

This will output the equivalent GMT date and time string for the input PT date string (2021-10-10T15:30:00-07:00), which is October 10th, 2021 at 10:30 PM GMT.

gistlibby LogSnag