简体   繁体   中英

Moment.js locale, format output array

I try to use moment.js to display days of this fortnight.

I use the french locale in order to display days like this :

  • lundi 13/3 // moment.js format = 'dddd D/M'. Lundi = Monday in french
  • mardi 14/3
  • etc.

After setting the moment.js locale in the head with

<script>
  moment.locale('fr');
</script>

The function bellow built an array with the right days (begining on Monday as set in the french locale), but I don't succeed to display this days in the format I want.

function thisFortnight() {

    var startFortnight = moment().startOf('week');
    var endFortnight = startFortnight.clone().add(13, 'd');

    var days = []
    var day = startFortnight;

    while (day <= endFortnight) {
        days.push(day.toDate());
        day = day.clone().add(1, 'd');
    }

    var eDisplayMoment = document.getElementById('Fortnight');
    eDisplayMoment.innerHTML = days;

}

Output :

Mon Mar 13 2017 00:00:00 GMT+0100 (CET),Tue Mar 14 2017 00:00:00 GMT+0100 (CET),Wed Mar 15 2017 00:00:00 GMT+0100 (CET),Thu Mar 16 2017 00:00:00 GMT+0100 (CET),Fri Mar 17 2017 00:00:00 GMT+0100 (CET),Sat Mar 18 2017 00:00:00 GMT+0100 (CET),Sun Mar 19 2017 00:00:00 GMT+0100 (CET),Mon Mar 20 2017 00:00:00 GMT+0100 (CET),Tue Mar 21 2017 00:00:00 GMT+0100 (CET),Wed Mar 22 2017 00:00:00 GMT+0100 (CET),Thu Mar 23 2017 00:00:00 GMT+0100 (CET),Fri Mar 24 2017 00:00:00 GMT+0100 (CET),Sat Mar 25 2017 00:00:00 GMT+0100 (CET),Sun Mar 26 2017 00:00:00 GMT+0100 (CET)

It should be : lundi 13/3, mardi 14/3, mercredi 15/3, etc.

I've tried a lot of solutions with .format('dddd D/M'), without success.

Thanks for your help

day.toDate() returns a native JS date, you want to use the moment object so use day.format('dddd D/M') .

eg

 var d = new moment(); console.log(d.format('dddd D/M')) function thisFortnight() { var startFortnight = moment().startOf('week'); var endFortnight = startFortnight.clone().add(13, 'd'); var days = [] var day = startFortnight; while (day <= endFortnight) { days.push(day.format('dddd D/M')); day = day.clone().add(1, 'd'); } var eDisplayMoment = document.getElementById('Fortnight'); eDisplayMoment.innerHTML = days.join('<br>'); } window.onload = thisFortnight; 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/locale/fr.js"></script> <div id="Fortnight"></div> 

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