Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current week

So i used momentjs to handle my date formats and get the current week.

But my question is how do i get it to start from monday to sunday.

getweek.js

function getCurrentWeek() {
  var currentDate = moment();

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

  var days = [];

  for (var i = 0; i <= 6; i++) {
    days.push(moment(weekStart).add(i, 'days').format("MMMM Do,dddd"));
  }
  console.log($scope.weekDays = days);
}

result

{0:"November 5th,Sunday"
1:"November 6th,Monday"
2:"November 7th,Tuesday"
3:"November 8th,Wednesday"
4:"November 9th,Thursday"
5:"November 10th,Friday"
6:"November 11th,Saturday"}

expected result

{0:"November 6th,Monday"
1:"November 7th,Tuesday"
2:"November 8th,Wednesday"
3:"November 9th,Thursday"
4:"November 10th,Friday"
5:"November 11th,Saturday"
6:"November 12th,Sunday"}

Thanks.

like image 942
Code.Freeze Avatar asked Nov 10 '17 01:11

Code.Freeze


People also ask

What is the current week number 2022?

Week 42. Week 42 is from Monday, October 17, 2022 until (and including) Sunday, October 23, 2022. The highest week number in a year is either 52 or 53.

Which is the current week?

The current Week Number is WN 40.

How do I get current week days in Javascript?

Javascript date getDay() method returns the day of the week for the specified date according to local time. The value returned by getDay() is an integer corresponding to the day of the week: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on.

How do I get the week in Python?

isoweekday() to get a weekday of a given date in Python The weekday() method we used above returns the day of the week as an integer, where Monday is 0 and Sunday is 6. Use the isoweekday() method to get the day of the week as an integer, where Monday is 1 and Sunday is 7.


2 Answers

You can use startOf('isoWeek') to start the week at Monday.

var weekStart = currentDate.clone().startOf('isoWeek');

function getCurrentWeek() {
  var currentDate = moment();

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

  var days = [];

  for (var i = 0; i <= 6; i++) {
    days.push(moment(weekStart).add(i, 'days').format("MMMM Do,dddd"));
  }
  console.log(days);
}

getCurrentWeek();
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.min.js"></script>
like image 176
Chava Geldzahler Avatar answered Oct 11 '22 20:10

Chava Geldzahler


Use 'isoweek' instead of 'week'

var currentDate = moment();

var weekStart = currentDate.clone().startOf('isoweek');

var days = [];

for (var i = 0; i <= 6; i++) {
    console.log(moment(weekStart).add(i, 'days').format("MMMM Do,dddd"));
}
like image 41
klugjo Avatar answered Oct 11 '22 20:10

klugjo