Home > Blockchain >  Why the Javascript Date() constructor prefixes the output year with a plus sign if the year is above
Why the Javascript Date() constructor prefixes the output year with a plus sign if the year is above

Time:02-11

The Date() constructor provides the following example outputs (notice dates above year 9999)

console.log(new Date(Date.UTC(2022,0,1)));  // output => 2022-01-01T00:00:00.000Z

console.log(new Date(Date.UTC(4000,0,1)));  // output => 4000-01-01T00:00:00.000Z

console.log(new Date(Date.UTC(9999,0,1)));  // output => 9999-01-01T00:00:00.000Z

console.log(new Date(Date.UTC(10000,0,1)));  // output =>  010000-01-01T00:00:00.000Z

console.log(new Date(Date.UTC(20000,0,1)));  // output =>  020000-01-01T00:00:00.000Z

For years above 9999 the output is a 6 digit number string prefixed with a 'plus' sign.

Is this correct? If not:

What is significant about year 9999?

Why is the " " sign added if the year is above 9999 while it is not added for lower years?

Tested with Chrome and Node and gives the same output.

Here are simple console outputs:

console.log(new Date(Date.UTC(2022,0,1)));  // output => 2022-01-01T00:00:00.000Z
console.log(new Date(Date.UTC(4000,0,1)));  // output => 4000-01-01T00:00:00.000Z
console.log(new Date(Date.UTC(9999,0,1)));  // output => 9999-01-01T00:00:00.000Z
console.log(new Date(Date.UTC(10000,0,1)));  // output =>  010000-01-01T00:00:00.000Z
console.log(new Date(Date.UTC(20000,0,1)));  // output =>  020000-01-01T00:00:00.000Z

CodePudding user response:

Is this correct?

The short answer is "yes".

Nothing to do with the Date constructor. Dates are just an offset in milliseconds from the ECMAScript epoch (1970-01-01T00:00:00Z), that's it.

What you are seeing is the result of calling Date.prototype.toISOString which creates a string for the date represented by the Date instance's time value as specified by ECMA-262 Date Time String Format.

For expanded years of more than 4 digits, the year is preceded by " " or "-" as appropriate.

  • Related