How to get the Days b/w current week in moment.js
Solution 1
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.
Solution 2
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;
}
Ranjith M
I'm a php programmer for about 2 years and well known with codeignitor framework, jquery, html5 etc... Now i'm exploring new technologies like angular.js, node.js, angular material etc..
Updated on June 19, 2022Comments
-
Ranjith M almost 2 years
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>
-
Ranjith M over 8 yearsThanks dude. That Worked...@J-D
-
Ranjith M over 8 yearshey, i want two buttons next,prev when i click next, the days in the next week must be shown. if i click prev the days in previous week must be shown.
-
Dhanushka almost 5 yearsweekEnd is not used