Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Locale detection with Moment.js

Tags:

momentjs

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

like image 703
RunLoop Avatar asked Sep 08 '14 13:09

RunLoop


People also ask

How do I set a moment in locale?

You set locale with moment. locale('de') , and you create a new object representing the date of now by moment() (note the parenthesis) and then format('LLL') it. The parenthesis is important.

Is MomentJS deprecated?

Moment construction falls back to js Date. This is discouraged and will be removed in an upcoming major release. This deprecation warning is thrown when no known format is found for a date passed into the string constructor.

What is Moment default locale?

lang(String, Object); By default, Moment. js comes with English (United States) locale strings. If you need other locales, you can load them into Moment.

What is Moment () in JavaScript?

MomentJS is a JavaScript library which helps is parsing, validating, manipulating and displaying date/time in JavaScript in a very easy way. This chapter will provide an overview of MomentJS and discusses its features in detail. Moment JS allows displaying of date as per localization and in human readable format.


1 Answers

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

like image 128
Joanvo Avatar answered Sep 28 '22 17:09

Joanvo