Reputation: 815
Using moment how can we convert localized date string to javascript date object? Followed below steps, but got Current Output(check below).
How can we get Expected Output?
Could you please help me.
Ex: Setting moment locale as 'fr'
moment.defineLocale('fr', [localeObject][1]);
Now we get the date string as "27 févr. 2020 18:23:50"
How can we convert it as dateobject?
moment("27 févr. 2020 18:23:50")
Expected output:
Thu Feb 27 2020 18:23:50 GMT+0530 (India Standard Time)
Current Output:
Invalid Date
Upvotes: 1
Views: 764
Reputation: 31502
You are getting Invalid Date because "27 févr. 2020 18:23:50"
is not in ISO 8601 nor in RFC 2822 compliant form, so you have to use moment(String, String)
. Moreover you have to use french locale, see i18n section of the doc.
As described in the docs, you can use DD
for days of the month, MMM
for month name (locale aware), YYYY
for 4 digit year, HH
for 0-23 hours (lowercase hh
for 1-12 hours), mm
for minutes and ss
for seconds.
Then you can use toDate()
to get a JavaScript date from a moment object:
To get a copy of the native Date object that Moment.js wraps, use
moment#toDate
.
Snippet with working code sample:
console.log( moment("27 févr. 2020 18:23:50", "DD MMM YYYY HH:mm:ss").toDate());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/locale/fr.js"></script>
Upvotes: 1