Home > Back-end >  Date.prototype.toLocaleDateString() problem
Date.prototype.toLocaleDateString() problem

Time:11-17

I'm working on a graphical listing of Roman emperors and ran into the following problem: The birth and death dates are stored in a JSON as a string. e.g. Julius Caesar:

"start":"-000100-07-12"

If I use the Date object

const date = new Date(caesar.start)

console.log(date)

//Date Object Thu Jul 12 -0100 00:53:28 GMT 0053 ...

... via console.log it works... but if I now want to render the object as a string with

date.toLocaleDateString("en-EN", {year : "numeric", era: "short"})

console.log gives me

"101 BC" instead of "100 BC"

the problem is easily reproducable.

I only found a similar description

for a different technology.

However, the problem seems to be the same.

A fix would be to write a custom toLocaleDateString function, because getFullYear(), getMonth() work as expected.

Has anyone had similar experiences, or a solution to the problem? I guess handling dates before 1582 is a bit hooky.... maybe it has to do with the fact that there is no year 0?

CodePudding user response:

Looks like the problem is in toLocaleDateString.

But separate methods work as expected

For example

date.getDate(); // 12
date.getFullYear(); // -100
date.getMonth(); // 6 (getMonth() starts with 0) 

You can get the same format with this methods.

CodePudding user response:

According to the ISO 8601 standard "-000100-07-12" represents 12th July 101 BCE and the date appears to be being parsed correctly.

It's just that the standard doesn't match our expectations as we almost always deal with positive years.

Unfortunately I'm unable to see what the "Cause" of the linked Oracle error is so it may be the same "issue"

  • Related