1

I am trying to read a CSV file. The date in the file in a format - 'DD-MMM-YY'. When I am trying to read this, I am getting an invalid date error. 01-Apr-20 - how do we read this in react?

Thanks In advance!

2 Answers2

2

If you can afford to use an external library, you can use moment.js.

Then, to read these dates, simply use the following line:

moment('01-Apr-20', 'DD-MMM-YY')

which returns a moment object (basically like a Date-object), with a lot of functionality.


To install:

Node.js / npm: npm install moment, then import it using require() or import moment from 'moment'.

Vanilla javascript: Add the following script tag to your html-code: <script src="https://momentjs.com/downloads/moment.js"></script>.

Sebastian
  • 1,321
  • 9
  • 21
  • 2
    I'll add a comment for anyone who wants to try out moment before installing it locally: Go to momentjs.com and open devtools console (`F12`). The `moment`-keyword is globally available there for testing. – Sebastian Jul 23 '20 at 11:32
  • how do we import moment? – Sailesh Sridhar Jul 23 '20 at 11:38
  • getting an error: moment is not defined, npm install moment -done – Sailesh Sridhar Jul 23 '20 at 11:39
  • To install moment: If you're using node/npm, then simply do `npm install moment`, then import it using `require()` or `import moment from 'moment'`. If you're using vanilla javascript, simply add the following script tag to your html-code: ``. Hope this helps. PS: Remember to mark an answer as correct if it works out! – Sebastian Jul 23 '20 at 11:55
-1

You don't need to put that extra 2nd parameter. Only the 1st parameter date would suffice to convert it to a javascript date type object. new Date('01-Apr-20')

If you need to show it in any particular format, you can use the date libraries packages e.g luxon (advantage of being less in size)

https://moment.github.io/luxon/docs/manual/formatting.html#presets

brijesh-pant
  • 967
  • 1
  • 8
  • 16
  • 1
    '01-Apr-20' is not a format supported by ECMA-262, so parsing is implementation dependent. See [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) In particular, parsing of two digit years is problematic: `new Date('01/02/90')` likely returns a date for 2 Jan 1990, not 1 Feb 2090 (which is how I would understand it). Also, `new Date('01-Apr-20')` returns an invalid date in Firefox. – RobG Jul 23 '20 at 12:55
  • Rightly said @RobG, parsing is implementation-dependent. – brijesh-pant Jul 23 '20 at 14:10