DEV Community

Cover image for Caveat of using javascript Date object constructor
Idris Akintobi
Idris Akintobi

Posted on

Caveat of using javascript Date object constructor

JavaScript's Date object provides powerful tools for working with dates, but it's important to be mindful of the timezone implications, especially in distributed systems.


Example Scenarios
1. Converting "YYYYMMDDHHMMSS" to Epoch Milliseconds
Imagine a scenario where an external service provides dates in the format "YYYYMMDDHHMMSS," and the task is to convert them to Unix timestamps (epoch milliseconds). The following function accomplishes this task:

function convertYMDHMSToEpoch(dateString) {
    const date = new Date(
        +dateString.substring(0, 4),
        +dateString.substring(4, 6) - 1,
        +dateString.substring(6, 8),
        +dateString.substring(8, 10),
        +dateString.substring(10, 12),
        +dateString.substring(12, 14)
    );
    return date.getTime().toString();
};
Enter fullscreen mode Exit fullscreen mode

However, it's crucial to note that this function may return different values depending on the timezone of the environment where the code is executed.

2. Converting ISO Date String to User-Friendly Format
Suppose you receive a date in ISO format, and the goal is to display it in a user-friendly format. The following code accomplishes this using the Date object constructor:

const isoString = '2023-01-01T23:00:00Z';
new Date(isoString).toString().substring(0, 24);
Enter fullscreen mode Exit fullscreen mode

Again, the issue here is that the output may vary based on the timezone of the runtime environment.


Testing with Different Timezones
To illustrate the impact of timezones, let's take the second example and test it with different timezones:

const isoString = '2023-01-01T23:00:00Z';

process.env.TZ = 'UTC-8';
new Date(isoString).toString().substring(0, 24); // Mon Jan 02 2023 07:00:00

process.env.TZ = 'UTC';
new Date(isoString).toString().substring(0, 24); // Sun Jan 01 2023 23:00:00
Enter fullscreen mode Exit fullscreen mode

The output will vary based on the runtime environment's timezone.


Best Practices

1. Default to UTC
Defaulting backend services to UTC is a widely adopted best practice. You can set the environment variable TZ to 'UTC' to enforce this.

export TZ = UTC
Enter fullscreen mode Exit fullscreen mode

OR

//setting the TZ environment variable to UTC
process.env.TZ = 'UTC'
Enter fullscreen mode Exit fullscreen mode

We can refactor the function in out first example to enforce UTC timezone with the Date constructor.

// Convert "YYYYMMDDHHMMSS" to milliseconds in UTC
mapToTimestamp(dateString) {
    const date = new Date(
        Date.UTC(
            +dateString.substring(0, 4),
            +dateString.substring(4, 6) - 1,
            +dateString.substring(6, 8),
            +dateString.substring(8, 10),
            +dateString.substring(10, 12),
            +dateString.substring(12, 14)
        )
    );
    return date.getTime().toString();
}
Enter fullscreen mode Exit fullscreen mode

Now, this function will return the same value in different timezones.

We can then convert to local time on the client side using the toLocaleString method:

const date = new Date('2023-01-01T12:00:00Z');

// Display in the system's timezone
const formattedDate = date.toLocaleString('en-US');

// Display in a specific timezone passed in the options (e.g., UTC)
const formattedDateUTC = date.toLocaleString('en-US', { timeZone: 'UTC' });
Enter fullscreen mode Exit fullscreen mode

2. Explore Date Manipulation Libraries
Consider using third-party date manipulation libraries like day.js or date-fns. These libraries offer more control over formatting and timezone handling, allowing you to create consistent and customized date displays across different environments.

// Example using day.js
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc.js';

dayjs.extend(utc);
process.env.TZ = 'America/New_York';

console.log(dayjs().utc().format()); // Output in UTC
console.log(dayjs().format()); // Output in America/New_York
Enter fullscreen mode Exit fullscreen mode

Conclusion
Considering time zones is essential for robust and reliable JavaScript applications. This combination of defaulting backend services to UTC and converting to local time on the client side promotes consistency in date and time handling throughout your application, contributing to a smoother user experience and mitigating potential issues related to timezone disparities. Date manipulation libraries can also be leveraged to ensure consistency.

Top comments (0)