0

I'm getting NaN on calculation of date in iOS. For desktop and Android, it works perfectly, but iOS and Safari, I get NaN

Here's my code:

last_visit_date is coming from the database, it comes ex: "2019-06-07T00:00:00.000Z"

let formattedLastVisitDate = moment(last_visit_date).format('MM-DD-YYYY') --- RESULT: "06-06-2019"

let testing = moment(formattedLastVisitDate).add('30', 'days').format('MM-DD-YYYY') -- RESULT "Invalid Date"

let add14Days = moment(testing).add('14', 'days').format('MM-DD-YYYY') -- RESULT "Invalid Date"

Why is this logic failing just on iOS?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
MCM
  • 141
  • 2
  • 15
  • See [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG Jul 11 '19 at 20:12

1 Answers1

4

In both moment(formattedLastVisitDate) and moment(testing), you are parsing a string in MM-DD-YYYY format. If you look on the developer console, you'll see that you get a deprecation warning. This is covered in the Moment.js guides here.

When parsing a string, either parse one of the supported string formats, or supply a formatting specification second argument, like so:

moment(formattedLastVisitDate, 'MM-DD-YYYY')

It fails on some browsers and not others for the reason described in the deprecation message, which is that it falls back to the built-in Date.parse behavior, which has some implementation-specific behavior, and thus varies across browsers.

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
  • No, OP is parsing a string in the `YYYY-MM-DDThh:mm:ss.mmmZ` format. (Which also isn't in the list of allowed formats in that link.) – David Knipe Jul 11 '19 at 19:33
  • 2
    Sorry, but incorrect on both points. The input string format is one that Moment supports without specifying. The docs don't go through every permutation, but explain the requirements for the date part, the separator, the time part, and the offset. `"2019-06-07T00:00:00.000Z"` is a supported string. The problem with the OP's code is that the `testing` and `add14Days` variables are string that are generated with the previous line's `.format('MM-DD-YYYY')` function are in a format not supported without a specification string. – Matt Johnson-Pint Jul 11 '19 at 19:44
  • To be clear, look at the comment the OP left as the result of the first line `RESULT: "06-06-2019"`. It's on the second line that that input format throws a deprecation warning and is rejected by some browsers. – Matt Johnson-Pint Jul 11 '19 at 19:45