Reputation: 8423
I just found an unexpected behavior where I have placed a timeStamp (Date
) inside a hidden form field. When submitting the (update) form I made some checks on the document delta (because I only want to update the differences of the editing).
At that point I faced, that the unedited hidden Date
field has been detected as being different.
I broke it down to the following reproduction code:
const date = new Date() // Mon Dec 10 2018 09:42:34 GMT+0100 (Timezone goes here)
const dateStr = date.toString()
console.log(date) // "2018-12-10T08:42:34.388Z"
console.log(new Date(dateStr)); // "2018-12-10T08:42:34.000Z"
It does only occur, when the date has been formatted to String (which for example happens when I assign it as value of a input field).
Can anyone explain why is that so?
Upvotes: 2
Views: 226
Reputation: 12737
The problem happens because .toString()
strips away the milliseconds part of the date.
When you try to reconstruct the date again from the string, the milliseconds part will be defaulted to zero, because it was not given/provided again.
Upvotes: 4
Reputation: 944442
Because toString()
converts the date to ISO 8601 with precision to the second.
The dates you are comparing differ by milliseconds.
Upvotes: 2