Search code examples
javascriptmomentjslocale

How to change the locale in moment.js


I know this probably looks like a duplicate question but I am unable to change my locale using moment in my React/ES6 setup.

This is what I have been able to gather from the internet but it doesn't work

import moment from 'moment';
import 'moment/min/locales';

moment.locale('en-gb');
moment('31/08/2021').format('YYYY-MM-DD') \\ returns 'Invalid Date'

Where am I going wrong?


Solution

  • This may not be the perfect way to do it but it 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'