Forem

Ayako yk
Ayako yk

Posted on

JavaScript Date Objects: Basics and Time Zone Adjustments

Data objects are among the key objects in JavaScript, offering a variety of useful methods for managing dates and times. When building applications that care for users across different time zones, careful handling of time zones and formatting becomes essential for accuracy and consistency. While third-party libraries provide powerful solutions for these tasks, this time, I'll focus on JavaScript's built-in Date objects.

JavaScript Date objects represent a single moment in time in a platform-independent format.
MDN

In other words, Date objects represent a specific moment and display a static date and time based on the browser's time zone.

Here are some examples from W3Schools. I reside on the west coast of Canada, which follows the Pacific Time Zone.

new Date()
new Date() without arguments creates a date object with the current date and time. By default, JavaScript outputs dates using the toString() method, which provides a string representation of the date, including the time zone.

const d = new Date();  
// DayOfWeek Month Day Year HH:MM:SS TimeZoneOffset (TimeZoneName)
// Sun Feb 09 2025 10:29:24 GMT-0800 (Pacific Standard Time)
Enter fullscreen mode Exit fullscreen mode

new Date(date string)
new Date(date string) creates a date object from a date string.

const d = new Date("October 13, 2014 11:13:00");
// Mon Oct 13 2014 11:13:00 GMT-0700 (Pacific Daylight Time)
Enter fullscreen mode Exit fullscreen mode

When the time is included, it is treated as local time, so the output matches the time in the argument.

const d = new Date("2022-03-25");
// Thu Mar 24 2022 17:00:00 GMT-0700 (Pacific Daylight Time)
Enter fullscreen mode Exit fullscreen mode

When only the date is provided, it is treated as UTC (Universal Time Coordinated or Coordinated Universal Time).

new Date(year, month, ...)
new Date(year, month, ...) creates a date object with a specified date and time.
Seven numbers specify year, month, day, hour, minute, second, and millisecond (in that order).
Note: The month is zero-based, meaning 0 represents January.

const d = new Date(2018, 11, 24, 10, 33, 30, 0);
// Mon Dec 24 2018 10:33:30 GMT-0800 (Pacific Standard Time)
Enter fullscreen mode Exit fullscreen mode

W3Schools

Timestamps

A JavaScript date is fundamentally specified as the time in milliseconds that has elapsed since the epoch, which is defined as the midnight at the beginning of January 1, 1970, UTC (equivalent to the UNIX epoch). This timestamp is timezone-agnostic and uniquely defines an instant in history.
MDN

Usage:
Timestamps are of type number. While they can be converted to strings, their native type is numeric, which allows for easy calculations and comparisons.

  1. Storing data in the database
  2. Comparing dates
  3. Performing data calculations
  4. Interfacing with APIs

How to get timestamps:
getTime()

const date = new Date(); 
const timestamp = date.getTime();
Enter fullscreen mode Exit fullscreen mode

or

const timestamp = new Date().getTime();
Enter fullscreen mode Exit fullscreen mode

Convert to Number

const date = new Date();
const timestamp = Number(date);
Enter fullscreen mode Exit fullscreen mode

Date.parse()

const date = Date.parse('Dec 24 2018 10:33:30 GMT-0800');
Enter fullscreen mode Exit fullscreen mode

Date.now()

const timestamp = Date.now();
Enter fullscreen mode Exit fullscreen mode

Which is Better?
--> Date.now()

It is semantically equivalent to new Date().getTime(), but it doesn’t create an intermediate Date object. So it’s faster and doesn’t put pressure on garbage collection.
The Modern JavaScript Tutorial

Disadvantage
It's not human-readable, so it needs to be converted for display in the UI.

How to convert timestamps to a human-readable format
new Date(timestamp)

const date = new Date(1739225718113);
console.log(date.toString());
// Mon Feb 10 2025 14:15:18 GMT-0800 (Pacific Standard Time)
Enter fullscreen mode Exit fullscreen mode

We can use these methods for customization:
toLocaleString()

console.log(date.toLocaleString());
// 2/10/2025, 2:15:18 PM
Enter fullscreen mode Exit fullscreen mode

toLocaleTimeString()

console.log(date.toLocaleTimeString());
// 2:15:18 PM
Enter fullscreen mode Exit fullscreen mode

Manually extract data

const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();

console.log(`${year}-${month}-${day}`);
// 2025-2-10
Enter fullscreen mode Exit fullscreen mode

Working on an Application Used Across Time Zones
As mentioned above, dates and times should be stored in a database as UTC timestamps. When displaying the date and time, we need to convert them to human-readable formats. Intl.DateTimeFormat comes in handy.

Intl.DateTimeFormat

The Intl.DateTimeFormat object enables language-sensitive date and time formatting.
MDN

The browser automatically converts the date and time to a user's local time, but we can specify the format to display, such as MM/DD/YYYY in the US, DD/MM/YYYY in Europe.

For instance, if we set it to the Japanese format, it looks like this:

const utcDate = new Date('2025-02-10T10:00:00Z'); // UTC time
const localDate = new Intl.DateTimeFormat('ja-JP', { 
    year: 'numeric', 
    month: 'long', 
    day: 'numeric', 
    hour: 'numeric', 
    minute: 'numeric', 
    second: 'numeric', 
    timeZoneName: 'short' 
}).format(utcDate);

console.log(localDate); // 2025年2月10日 19:00 JST
Enter fullscreen mode Exit fullscreen mode

However, I got this result: 2025年2月10日 2:00:00 GMT-8 since I'm outside Japan. To get the Japanese time, I needed to explicitly add timeZone: 'Asia/Tokyo'.

const utcDate = new Date('2025-02-10T10:00:00Z'); // UTC time
const localDate = new Intl.DateTimeFormat('ja-JP', { 
    year: 'numeric', 
    month: 'long', 
    day: 'numeric', 
    hour: 'numeric', 
    minute: 'numeric', 
    second: 'numeric', 
    timeZoneName: 'short',
    timeZone: 'Asia/Tokyo' // Explicitly set the time zone to JST (Tokyo)
}).format(utcDate);

console.log(localDate); 
Enter fullscreen mode Exit fullscreen mode

Now, I get 2025年2月10日 19:00:00 JST.

This setting will depend on how the application is designed to work. As the nature of work is changing, with an increasing number of outsourcing employments, it's important to consider these factors within a development team. Ensuring correct handling of time zones can greatly improve the user experience in a globalized work environment.

Top comments (0)