Reputation: 9289
I am trying to print the current week from Mon to Sun using moment.js as
I saw moment().format('ddd, MMM Do')
can print the desired format. And moment().startOf('week').toString()
gives the correct first day of week but in different format.
moment.adḍ̣(1, 'day')
can give next day and so on.
My trouble is how to combine this to print all days of the week starting from first day.
Upvotes: 3
Views: 1394
Reputation: 14462
You don't need to call moment().startOf('week').toString()
like that. toString()
just converts object to its string representation, but the information that you need is contained within the object obtained by calling moment().startOf('week')
.
If you want the mentioned format then you can easily change it to moment().startOf('week').format('ddd, MMM Do')
. And then just keep adding days (using add(i, 'days')
) to that start of the week in a loop until you have obtained 7 days, each time calling .format('ddd, MMM Do')
on a given date.
const dateStr = '';
for (let i = 0; i < 7; i++) {
console.log(moment().startOf('week').add(i, 'days').format('ddd, MMM Do'));
}
<script src="https://rawgit.com/moment/moment/2.2.1/min/moment.min.js"></script>
And if you need it as a string.
const date = Array.from({length: 7}, () => 0)
.map((v, i) => moment().startOf('week').add(i, 'day').format('ddd, MMM Do'))
.join('; ');
console.log(date);
<script src="https://rawgit.com/moment/moment/2.2.1/min/moment.min.js"></script>
Upvotes: 1
Reputation: 1513
Here weekDateStr
will contain formatted string for current week
var weekDateStr = [];
var date = moment().startOf('week');
for(var i = 0; i < 7; i++) {
console.log(date.format('ddd, MMM Do'));
weekDateStr.push(date.format('ddd, MMM Do'));
date = date.adḍ̣(1, 'day')
}
console.log(weekDateStr);
Upvotes: 3