Home > other >  Creating a date object from a date string and locale
Creating a date object from a date string and locale

Time:09-17

I'm not sure if this is going to be a duplicated question as I couldn't find anything on SO therefore, I'm going ahead with this question -

I have a date string which is locale-dependent and I have the locale info with it too.

Eg. dateStr = '06/07/2021' and locale='en-GB'.

How do I get a JS Date object from this? The Date constructor doesn't seem to take a locale and by default parses it with respect to the en-US locale(MM-DD-YYYY).

By this I mean, that the above dateStr will be converted to 7th June 2021 and not the actual 6 July 2021 using the Date constructor.

UPDATE:
I got something from d2l-intl but it doesn't work. Quite strange.

var parser = new d2lIntl.DateTimeParse('en-GB');
var date = parser.parseDate('23/05/2021');
console.log(
    date.getMonth(),
    date.getDate()
);

which breaks as it still accepts date string in en-US format.

CodePudding user response:

Looking at the question's comments, I believe sometimes people just don't understand the question and start blaming the problem itself. It's ridiculous :D

This may not be the perfect way to go about it (there can be something cleaner and shorter), but this definitely works.

locale = 'en-GB';
value = '07/06/2021';


moment.locale(locale);
const localeData = moment.localeData();
const format = localeData.longDateFormat('L');
console.log(moment(value, format).format('YYYY-MM-DD')); // '2021-06-07'
  • Related