create a date in a timezone in typescript

To create a date in a specific timezone in Typescript, you can use the toLocaleString() method. Here is an example:

index.ts
const date = new Date();
const timeZone = 'America/New_York';

const datetimeInTimezone = date.toLocaleString('en-US', { timeZone });

console.log(datetimeInTimezone); // Output: '2/22/2022, 12:00:00 AM'
204 chars
7 lines

In the code above, we created a new Date object, and set the target timezone to 'America/New_York'. We then used the toLocaleString() method to format the date in the specified timezone, and saved the result in the datetimeInTimezone variable.

Note that the toLocaleString() method accepts several options to control the formatting of the output, such as the locale or the time format. You can find more details about these options in the TypeScript Date documentation.

gistlibby LogSnag