How to Format Dates and Times in JavaScript Using Timezones

Mar 06, 2023 | O. Wolfson
How to Format Dates and Times in JavaScript Using Timezones

Image from Unsplash

Working with dates and times is a common task in many JavaScript projects. However, formatting them correctly according to different timezones can be a bit challenging. This is where the formatDate function comes in handy, allowing you to easily format dates and times in any valid timezone. In this article, we'll take a closer look at how the formatDate function works and provide an example of how to use it to format dates and times in different timezones.

First, let's break down the code:

export const formatDate = (date) => {
  const dateObj = new Date(date);
  const options = { timeZone: "Asia/Bangkok" };
  const formattedDate = dateObj.toLocaleDateString("en-US", options);
  const formattedTime = dateObj.toLocaleTimeString("en-US", options);
  const formattedDateTime = `${formattedDate} ${formattedTime}`;
  return formattedDateTime;

The function formatDate takes in a single argument date, which is a JavaScript date object. The function creates a new Date object using the date argument and sets the options object to include the timeZone property with the value of "Asia/Bangkok". This sets the timezone for the date object to the timezone of Bangkok, Thailand.

The function then uses the toLocaleDateString and toLocaleTimeString methods of the Date object to format the date and time strings in the specified timezone. Finally, the function returns the formatted date and time as a string.

To use this function, you can call it and pass in a JavaScript date object as the argument. Here's an example:

const myDate = new Date(); // create a new date object with the current date and time
const formattedDateTime = formatDate(myDate); // format the date and time using the formatDate function
console.log(formattedDateTime); // output the formatted date and time string

Note that the timeZone option in the options object is set to "Asia/Bangkok". You can change this value to any valid timezone string, such as "America/New_York" or "Europe/London", to format the date and time in a different timezone.

As for the input delivery, the function expects a JavaScript Date object as its input. The timezone option is specified within the function itself, so it does not depend on the location of the user's computer. However, if you want to use a different timezone, you can modify the options object accordingly.