Trying to understand how moment.js is converting a string to date, I've bounced into this issue.
let date = "User has logged in to more than 10 .";
console.log(moment(date)); //output date
let invalid = "User has logged in to more than 10 a";
console.log(moment(invalid)); //output invalid date
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.js
"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-range/2.2.0/moment-range.js"></script>
can someone explain it to me ??
When you pass the string
moment
checks whether it is a valid date format, and if not, it falls back to the built-in javascriptDate.parse()
method.The moment.js docs say:
Date.parse
does not recognize anything useful in your string until it encounters10
; it drops the rest. A default date format is assumed, which will depend on your location and language. In my own case, here in the US, the format isMM/DD
. The result is that the string is parsed to a date of Oct. 1st (10th month, no day specified defaults to the 1st). And then (for Y2K-ish reasons, I suspect) it assumes a year of 2001, since no year is given.We get the same behavior from javascript's built-in
Date
methods:In your second case, you tried ending the string with
10 a
instead of10 .
and you will notice the same behavior (invalid date
) if you pass the same to the built-inDate
methods.