0

I'm working on a react app with firebase firestore for the db, the app stores a date field obtained from a datepicker in dd/mm/yyyy format as a string. I need to sort by dates and I'm converting dates to correctly sort by numbers with:

new Date(myDate).getTime()

But I'm getting NaN only on certain dates, for example:

01/12/2017 // 1484190000000
02/11/2017 // 1486782000000
22/08/2017 // NaN

Any idea???

user3785328
  • 674
  • 7
  • 6
  • In JS, Date constructor expects values in `MM/DD/YYYY` or `YYYY/MM/DD` but not in `DD/MM/YYYY`. You can try a simple trick: `new Date(dateStr.split('/').reverse().join('/'))` – Rajesh Dec 15 '17 at 08:39
  • 1
    In `22/08/2017`, `22` is not a valid month. Hence `NaN`. – 31piy Dec 15 '17 at 08:39
  • how about considering using `react-moment` ? – Lokesh Pandey Dec 15 '17 at 08:39
  • 1
    @Rajesh—the built-in date parser is not required to support any of those formats so it's not sensible to expect that it will. – RobG Dec 15 '17 at 09:28

1 Answers1

1
var dateArr = '22/08/2017'.split('/');
new Date(dateArr[2], --dateArr[1], dateArr[0]).getTime();

Try this. 22/08/2017 - wrong format, need 08/22/2017

Vladislav Latish
  • 307
  • 1
  • 10