简体   繁体   中英

Javascript moment.js - Date and Time in Spanish

I have the following code:

 /* ------------------------------------------------------------------------
  * SETTING DATE AND TIME
  * ------------------------------------------------------------------------
  */
 var datetime = null,
     date = null;
 var update = function() {
     date = moment(new Date());
     datetime.html(date.format('dddd, D MMMM  YYYY, h:mm:ss a'));
 };
 datetime = $('#time-date');
 update();
 setInterval(update, 1000);

Which updates an HTML div with current date and time.

I got the following output:

Sunday 28 January 2018, 11:31:51 am

I would like to get the same output but in Spanish:

Domingo 28 Enero 2018, 11:31:51 am

I have tried this post without success:

 var update = function() {
     date = moment(new Date());
     moment.locale('es');
     date.locale(false);
     datetime.html(date.format('dddd, D MMMM  YYYY, h:mm:ss a'));
 };

It does not change anything, the output is still the same.

You need to load the locale you need, besides moment(.min).js itself. Use:

require('moment/locale/es.js');

if you use node, or include the locale file traditionally, for example:

<script src="{path-to-moment-lib}/locale/es.js">

Note: I strongly advise against using moment-with-locales.js , even in minified version. It's huge (~15k lines) and it loads all locales. That's only for websites that need to display multiple locales on the same page and are truly international. It has significant overhead. If you need up to 3-4 languages, it's much better to only load the locale files you need.

There is different download options in moment.js's website

Moment.js with locales

moment-with-locales.js

Moment.js with locales (minified version)

moment-with-locales.min.js

After swapping this version with your current version you can learn how to customize things from here such as locales.

More performant option

Your other option is just download the specific locale file and implement it if you don't want to download all locales which is a better option.

Your options in Spanish are :

Spanish [es]

Spanish (United States) [es-us]

Spanish (Dominican Republic) [es-do]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM