Caveat of using javascript Date object constructor
Tags: javascript, typescript, node, react
Published: 2023-12-24 13:42:27

_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:
```javascript
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();
};
```
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:
```javascript
const isoString = '2023-01-01T23:00:00Z';
new Date(isoString).toString().substring(0, 24);
```
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:
```javascript
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
```
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.
```bash
export TZ = UTC
```
OR
```javascript
//setting the TZ environment variable to UTC
process.env.TZ = 'UTC'
```
We can refactor the function in out first example to enforce UTC timezone with the Date constructor.
```javascript
// 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();
}
```
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:
```javascript
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' });
```


**_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.
```javascript
// 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
```
---

**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.