2

I am working on a React Native application which is available on two languages (English & Spanish). Getting date in English is fine but for Spanish, Momentjs is not able to convert it to moment object for certain months(in spanish) like Abril, It throws Invalid date as output, while other month like Septiembre is working fine and it is getting converted to moment object.

const aprilDateES = moment("09 Abril, 2021") // Invalid date
const septeDateEs = moment("09 Septiembre, 2021") // Thu Sep 09 2021 00:00:00 GMT+0530

It is also throwing warning for Abril month - Warning message

My goal is to convert all Spanish date/month to moment object so that it can be converted to other format like DD/MM/YYYY and can also be validated using momentJS.

Here's the link to playground - https://replit.com/@DevAk1/MomentJSSpanishDate#src/App.jsx

Dev AKS
  • 512
  • 1
  • 5
  • 17
  • have you tried setting locale ? – Madhawa Priyashantha Sep 09 '21 at 16:42
  • Yes, I tried this import('moment/locale/es-us') and import('moment/locale/es') – Dev AKS Sep 09 '21 at 16:44
  • 1
    Don't? JS basically caught up to what moment.js was invented for way back when, and so you are [strongly discouraged](https://momentjs.com/docs/#/-project-status/) from using it anymore by the folks that made this library. Don't follow through on your goal to convert all Spanish date/month to moment object. Turn them into modern plain JS using Date and [DateTimeFormatter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) – Mike 'Pomax' Kamermans Sep 09 '21 at 17:11

1 Answers1

0

Change import to -

import moment from 'moment/min/moment-with-locales'

Then use this -

const date = moment('09 Abril, 2021', 'DD MMMM, YYYY', 'es').locale('en') 
// Fri Apr 09 2021 00:00:00 GMT+0530

Note - This is specific to format and language. Please change the source/target language and the date format according to the requirement.

Dev AKS
  • 512
  • 1
  • 5
  • 17