How to get the Days b/w current week in moment.js

Ranjith M picture Ranjith M · Jan 19, 2016 · Viewed 8.1k times · Source

I'm new to angular js and moment.js i have the following code which gives the start day and end day of a week like January 17th-January 23rd. but i want all the 7 days in this format january 17, monday.

My code

var currentDate,
weekStart,
weekEnd,
shortWeekFormat = 'MMMM Do';

function setCurrentDate(aMoment){
currentDate = aMoment,
weekStart = currentDate.clone().startOf('week'),
weekEnd = currentDate.clone().endOf('week')
}

setCurrentDate(moment());
$scope.currentWeek = function(){ return currentDate.format(shortWeekFormat);         };
$scope.currentWeekStart = function(){ return weekStart.format(shortWeekFormat); };
$scope.currentWeekEnd = function(){ return weekEnd.format(shortWeekFormat); };

HTML

<h2><i class="fa fa-arrow-left"></i>Week Of {{currentWeek()}}{{currentWeekStart()}}-{{currentWeekEnd()}}<i class="fa fa-arrow-right"></i></h2>
<button ng-click="prevWeek()">previous week</button>
<button ng-click="nextWeek()">next week</button>

Answer

J-D picture J-D · Jan 19, 2016

The format you want can be achieved with below moment code.

moment('01/19/2016').format("MMMM Do,dddd");

Now, to get all dates between a week you need to use array which holds all the seven dates for you. With simple for loop adding days to start date you can achieve what you want. Take a look at below sample code.

   var currentDate = moment();
   var weekStart = currentDate.clone().startOf('week');
   var weekEnd = currentDate.clone().endOf('week');

   var days = [];
   for (i = 0; i <= 6; i++) {

       days.push(moment(weekStart).add(i, 'days').format("MMMM Do,dddd"));

   };
   console.log(days);
   console.log(moment('01/19/2016').format("MMMM Do,dddd"));

Now to use it with angular you can assign days array to some scope variable and use ng-repeat to display dates.

JSFiddle