Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
like image 726
Ranjith M Avatar asked Dec 06 '22 19:12

Ranjith M


2 Answers

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

like image 163
J-D Avatar answered Jan 19 '23 06:01

J-D


Improving J-D's answer. This will return an array of moment objects:

const getCurrentWeekDays = () => {
  const weekStart = moment().startOf('week');

  const days = [];
  for (let i = 0; i <= 6; i++) {
    days.push(moment(weekStart).add(i, 'days'));
  }

  return days;
}
like image 27
Dhanushka Avatar answered Jan 19 '23 05:01

Dhanushka