I get for example: 1day ago. What I need is to set for different language, for example for de
. Any suggestion how can I do that?
moment(Date.
See official docs on how changing locale globally.
Note that you have to import locale data (e.g. moment-with-locales.min.js)
Here a working example:
moment.locale('de');
console.log(moment(Date.now()).fromNow()); //vor ein paar Sekunden
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment-with-locales.min.js"></script>
You can also use only data for a given locale (e.g. de
):
moment.locale('de');
console.log(moment(Date.now()).fromNow()); //vor ein paar Sekunden
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/locale/de.js"></script>
Moreover you are redefining moment in your code, that is incorrect
var moment = moment();
for example I want to use 'fa' locale
import moment from 'moment'
import fa from 'moment/locale/fa'
moment.locale('fa', fa)
EDIT: In the current version of moment.js this solution still works but it will output a message to the console that states you should use a new method called updateLocale. So the new solution should look like:
Updated solution
import moment from 'moment';
import localization from 'moment/locale/fr';
moment.updateLocale('fr', localization);
Previous Solution
You can change moment locale globally like that:
import moment from 'moment';
import localization from 'moment/locale/fr';
moment.locale('fr', localization);
I hope this helps you.
To build onto the answer by Gapur, how I got it to work (React native) was like this,
... other imports
import moment from "moment";
import russianLocale from "moment/locale/ru";
import englishLocale from "moment/locale/en-gb";
import chineseLocale from "moment/locale/zh-cn";
const Component = ({ ...props, language }) => {
moment.locale(language);
... logic
// wherever 'moment' is used, it's displayed in
// the language that is indicated by the language prop
... other logic
moment version 2.24.0