Moment converting digit into date

61 views Asked by At

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 ??

CodePen link

1

There are 1 answers

1
Jeff McMahan On

When you pass the string moment checks whether it is a valid date format, and if not, it falls back to the built-in javascript Date.parse() method.

The moment.js docs say:

When creating a moment from a string, we first check if the string matches known ISO 8601 formats, we then check if the string matches the RFC 2822 Date time format before dropping to the fall back of new Date(string) if a known format is not found.

Date.parse does not recognize anything useful in your string until it encounters 10; 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 is MM/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:

new Date(Date.parse('User has logged in to more than 10.'))
// Mon Oct 01 2001 00:00:00 GMT-0400 (EDT) <- As printed from Michigan.

In your second case, you tried ending the string with 10 a instead of 10 . and you will notice the same behavior (invalid date) if you pass the same to the built-in Date methods.