šŸŒ Time Zones and Date Formats in JavaScript

dhrn

Dharan Ganesan

Posted on February 21, 2023

šŸŒ Time Zones and Date Formats in JavaScript

ā° Handling Time Zones

One of the most critical aspects of working with time in web applications is handling different time zones. JavaScript's built-in Date object uses the browser's time zone by default, which can cause problems when working with users in different time zones.

We can use the Intl API to work with time zones in JavaScript. The Intl.DateTimeFormat constructor provides a way to create localized date and time strings, including the time zone.

const date = new Date();
const options = { dateStyle: 'full', timeStyle: 'long' };
const formatter = new Intl.DateTimeFormat(undefined, options);
const formattedDate = formatter.format(date);
Enter fullscreen mode Exit fullscreen mode
const date = new Date();
const options = { dateStyle: 'full', timeStyle: 'long', timeZone: 'America/Los_Angeles' };
const formatter = new Intl.DateTimeFormat(undefined, options);
const formattedDate = formatter.format(date);
Enter fullscreen mode Exit fullscreen mode

šŸ“… Formatting Dates and Times

In addition to handling time zones, we can use the Intl API to format dates and times in a variety of ways. The Intl.DateTimeFormat constructor we used earlier provides a range of options to customize the date and time formats, including:

  • dateStyle and timeStyle to specify the style of the date and time strings.
  • weekday, year, month, day, hour, minute, and second to specify which parts of the date and time to include.
  • hour12 to specify whether to use a 12-hour or 24-hour clock.
function formatDate(dateString, timeZone) {
  const date = new Date(dateString);
  const options = { dateStyle: 'medium', timeZone };
  const formatter = new Intl.DateTimeFormat(undefined, options);
  return formatter.format(date);
}
Enter fullscreen mode Exit fullscreen mode
function formatTime(dateString, timeZone) {
  const date = new Date(dateString);
  const options = { timeStyle: 'short', timeZone };
  const formatter = new Intl.DateTimeFormat(undefined, options);
  return formatter.format(date);
}
Enter fullscreen mode Exit fullscreen mode

ā²ļø Displaying Relative Time

Another common use case for displaying time in web applications is showing the time elapsed since an event occurred. We can use the Intl.RelativeTimeFormat constructor to create a string representing a relative time.

In addition to the above utility functions, we can also leverage the power of the RelativeTimeFormat API to display relative time information in a more user-friendly manner.

For example, instead of displaying "4 hours ago" for a message timestamp, we can display "Yesterday at 3:45 PM" or "Tuesday at 10:30 AM" depending on the actual date of the message.

function ChatMessage({ message, currentUser }) {
  const timestamp = new Date(message.timestamp);
  const locale = currentUser.locale;
  const relativeTimeFormat = new Intl.RelativeTimeFormat(locale, {
    numeric: "auto",
  });
  const now = new Date();

  // calculate the difference between the message timestamp and the current time
  const diffInMilliseconds = now.getTime() - timestamp.getTime();
  const diffInSeconds = Math.round(diffInMilliseconds / 1000);
  const diffInMinutes = Math.round(diffInSeconds / 60);
  const diffInHours = Math.round(diffInMinutes / 60);
  const diffInDays = Math.round(diffInHours / 24);

  // determine the appropriate relative time string based on the time difference
  let relativeTimeString;
  if (diffInSeconds < 60) {
    relativeTimeString = relativeTimeFormat.format(-diffInSeconds, "second");
  } else if (diffInMinutes < 60) {
    relativeTimeString = relativeTimeFormat.format(-diffInMinutes, "minute");
  } else if (diffInHours < 24) {
    relativeTimeString = relativeTimeFormat.format(-diffInHours, "hour");
  } else if (diffInDays < 7) {
    relativeTimeString = relativeTimeFormat.format(-diffInDays, "day");
  } else {
    relativeTimeString = new Intl.DateTimeFormat(locale).format(timestamp);
  }

  return (
    <div className="chat-message">
      <div className="message-username">{message.username}</div>
      <div className="message-timestamp">{relativeTimeString}</div>
      <div className="message-text">{message.text}</div>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

By using the RelativeTimeFormat API, we can provide a more user-friendly and localized way of displaying relative time information in our application.

šŸŽ‰ Congratulations, you have now learned how to handle time zones and date formats in JavaScript using the Intl API.

šŸ’– šŸ’Ŗ šŸ™… šŸš©
dhrn
Dharan Ganesan

Posted on February 21, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related