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.now()).fromNow()
I tried this:
<script>
var moment = moment();
moment.locale('de');
</script>
but get an error:
moment is not a function
In the docs, you can create language specific instances of moment by doing that. If you format first, the language won't process. Alternatively, you could do something like var deMoment = moment(); deMoment. lang('de') and reuse deMoment instead of moment throughout your script.
If you are changing locales frequently, you may want to know what locale is currently being used. This is as simple as calling moment. locale without any parameters.
By default, moment objects are created in the local time zone. Local time zone - it's a time zone which is set in a browser or on your node.js server. To change the default time zone, use moment.tz.setDefault with a valid time zone.
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With