73

I am using Moment.js in my project and formatting dates as follows:

var date = moment.unix(1318781876);
return date.format('LLLL');

The moment docs state the multiple locales are supported. I would like to know if moment.js will auto-detect the locale, or do I need to detect the locale and pass it to moment?

Update My goal is to ensure the displayed date is in the format of the user's region. i.e. in the US the short date format is mm/dd/yy whereas in the UK it is dd/mm/yy

RunLoop
  • 19,716
  • 21
  • 92
  • 151

2 Answers2

154

As of momentjs documentation:

By default, Moment.js comes with English locale strings. If you need other locales, you can load them into Moment.js for later use.

You can change it with that:

moment.locale(locale);

To get the user's locale with javascript you can do that:

var locale = window.navigator.userLanguage || window.navigator.language;

Refer to: http://momentjs.com/docs/#/i18n/changing-locale/

and JavaScript for detecting browser language preference

Community
  • 1
  • 1
Joanvo
  • 5,426
  • 2
  • 23
  • 35
  • 2
    So, it stands to reason that the following code could be used directly after loading moment-with-locale.js to ensure moment uses the correct locale for your users throughout the page: moment.locale(window.navigator.userLanguage || window.navigator.language). Is that a correct statement? – Brad Feb 01 '17 at 17:04
  • What if a user uses English but lives in China? – Grey Li Jul 09 '17 at 08:27
  • 3
    @GreyLi that is to ensure correct display of dates (i.e. english format), OP is not talking about timezones. In your case the displayed format would be english. – Joanvo Jul 10 '17 at 07:03
-2
import moment from 'moment';  
import 'moment/locale/fr';  
moment.locale('fr')

View issue comment

Syscall
  • 18,131
  • 10
  • 32
  • 49
  • 1
    I don't understand how this answers the question. You would have to dynamically load the locale module according to the region, so you are moving of detecting the locale from calling momentjs to loading the appropriate module. Moreover, the question mentions UK/US and your answer talks about French. – Kineolyan Mar 23 '21 at 10:44