DEV Community

Jen C.
Jen C.

Posted on

JavaScript – The Boundary of Date

Resource

Date objects encapsulate an integral number that represents milliseconds since the midnight at the beginning of January 1, 1970, UTC (the epoch).

Background

Recently, we encountered an issue related to retrieving the milliseconds of a Date object for calculations by calling getTime().

The bug occurred because the system did not account for negative values returned by getTime() when the selected date is earlier than January 1, 1970. As a result, both the backend and frontend need to address this limitation and align on a solution.

Some experiments to test the boundaries

The last moment before 1970:

const lastMomentBefore1970 = new Date('1969-12-31T23:59:59.999Z');

console.log(lastMomentBefore1970.getTime());
Enter fullscreen mode Exit fullscreen mode

Output

[LOG]: -1 
Enter fullscreen mode Exit fullscreen mode

The moment right at 1970:

const epochMoment = new Date('1970-01-01T00:00:00.000Z');

console.log(epochMoment.getTime());
Enter fullscreen mode Exit fullscreen mode

Output

[LOG]: 0 
Enter fullscreen mode Exit fullscreen mode

The moment right after 1970:

const firstMomentAfter1970 = new Date('1970-01-01T00:00:00.001Z');

console.log(firstMomentAfter1970.getTime());
Enter fullscreen mode Exit fullscreen mode

Output

[LOG]: 1 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

OSZAR »