简体   繁体   中英

Date format - momentjs - extract date and time separately using locale language

I am using moment.js library I have a date in this format :

2014-08-07T10:00:00+02:00

I want to have two separate values :

- Thursday, August 7 2014
- 10 am

But I also want them to be using the local language. For example, if moment.lang("fr"), the output should be

- Jeudi 7 Août 2014
- 10h

I set the moment.js lang in the correct way. I managed to remove hour,minutes and seconds (to extract the first value) :

new Date(moment.utc(date).format('LL')) //Outputs Thu Aug 07 2014 00:00:00 GMT+0200 (Paris, Madrid)

But I don't know how to extract the hour and minutes (for the second value) and how to show the date using the current language .

@Rayjax solution is not working anymore in recent versions of moment.js. Behavior of moment.localeData().longDateFormat() changed. LT is now already replaced by time format. Instead of dddd, MMMM D, YYYY LT it returns now dddd, MMMM D, YYYY h:mm A . Therefore removing LT from string does not work anymore. But we could just remove compiled LT for current locale:

moment.localeData().longDateFormat('LLLL')
.replace(
  moment.localeData().longDateFormat('LT'), '')
.trim();

Trim is necessary to avoid unnecessary white spaces.

Hi I don't know if it's the best way do to it but it's working

moment.locale("en");

var now = moment()

console.log(now.format(moment.localeData().longDateFormat('LLLL').replace('LT' , '')));

console.log(now.format(moment.localeData().longDateFormat('LT').replace('mm' , '').replace(':' , '').replace('.' , '')))

http://jsfiddle.net/yann86/tb0u5eav/

I came up with this which works well :

moment.lang("fr"); //en, es or whatever
var date = moment(dateParam).format("LL"), 
time = moment(dateParam).format("LT");
console.log(date, time) -- outputs separatedly date and time in the correct language form

What I was missing were the language configs files : http://momentjs.com/ i grabbed momentjs+locales instead of moment.js only and it worked.

It is important to note that moment.js won't tell you you are missing those filed, it will just default to english.

It worked for my needs:

moment().locale('en').format('L');
moment().locale('pt-br').format('L');

Just change the format for your needs. The Documentation of the moment is great. http://momentjs.com/

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