Ashish Sharma
Ashish Sharma

Reputation: 679

Converting to same date format using format of Moment JS gives invalid date

I have a react application where at one place we are converting date using moment like this

moment("08/19/1994", 'DD/MM/YYYY', true).isValid()

this returns the date as "19/08/1994 and this value is stored in redux store.

When the component is again refreshed, this conversion happens again and this time it works like this

moment("19/08/1994", 'DD/MM/YYYY', true).isValid() //invalid date.

So if we are converting same date format it is giving the error So is there a way we can check the format or git rid of this invalid date using any other method.

Upvotes: 0

Views: 198

Answers (2)

manuAcl
manuAcl

Reputation: 311

You should convert the date only the first time you store it in redux, not in the react component.

Upvotes: 1

User863
User863

Reputation: 20039

isValid() returns boolean based on the date validity

Use format() to convert date to 'DD/MM/YYYY'

console.log(moment("08/19/1994", 'MM/DD/YYYY').format('DD/MM/YYYY'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

Upvotes: 0

Related Questions