Minimum and maximum date
I was wondering which is the minimum and the maximum date allowed for a Javascript Date
object. I found that the minimum date is something like 200000 B.C., but I couldn't get any reference about it.
Does anyone know the answer? I just hope that it doesn't depend on the browser.
An answer in "epoch time" (= milliseconds from 1970-01-01 00:00:00 UTC+00) would be the best.
From the spec, §15.9.1.1:
A Date object contains a Number indicating a particular instant in time to within a millisecond. Such a Number is called a time value. A time value may also be NaN, indicating that the Date object does not represent a specific instant of time.
Time is measured in ECMAScript in milliseconds since 01 January, 1970 UTC. In time values leap seconds are ignored. It is assumed that there are exactly 86,400,000 milliseconds per day. ECMAScript Number values can represent all integers from –9,007,199,254,740,992 to 9,007,199,254,740,992; this range suffices to measure times to millisecond precision for any instant that is within approximately 285,616 years, either forward or backward, from 01 January, 1970 UTC.
The actual range of times supported by ECMAScript Date objects is slightly smaller: exactly –100,000,000 days to 100,000,000 days measured relative to midnight at the beginning of 01 January, 1970 UTC. This gives a range of 8,640,000,000,000,000 milliseconds to either side of 01 January, 1970 UTC.
The exact moment of midnight at the beginning of 01 January, 1970 UTC is represented by the value +0.
The third paragraph being the most relevant. Based on that paragraph, we can get the precise earliest date per spec from new Date(-8640000000000000)
, which is Tuesday, April 20th, 271,821 BCE (BCE = Before Common Era, e.g., the year -271,821).
To augment T.J.'s answer, exceeding the min/max values generates an Invalid Date.
let maxDate = new Date(8640000000000000);
let minDate = new Date(-8640000000000000);
console.log(new Date(maxDate.getTime()).toString());
console.log(new Date(maxDate.getTime() - 1).toString());
console.log(new Date(maxDate.getTime() + 1).toString()); // Invalid Date
console.log(new Date(minDate.getTime()).toString());
console.log(new Date(minDate.getTime() + 1).toString());
console.log(new Date(minDate.getTime() - 1).toString()); // Invalid Date
A small correction of the accepted answer; the year of the minimum date is actually 271,822 BCE, as you can see when running the following snippet:
console.log(new Date(-8640000000000000).toLocaleString("en", {"year": "numeric", "era": "short"}))
Indeed, year -271,821 is actually 271,822 BCE because JavaScript's Date
(along with ISO 8601) uses astronomical year numbering, which uses a year zero.
Thus, year 1 is 1 CE, year 0 is 1 BCE, year -1 is 2 BCE, etc.