6

I want to get the first (monday) and the last (sunday) day of the previous week in javascript. I already checked other topics, but it doesn't work. I also need to handle if the previous week is on 2 differents months.

I'm using this code, but the lastsunday is 06/03/2014 instead of 06/04/2014

var beforeOneWeek = new Date(new Date().getTime() - 60 * 60 * 24 * 7 * 1000)
  , day = beforeOneWeek.getDay()
  , diffToMonday = beforeOneWeek.getDate() - day + (day === 0 ? -6 : 1)
  , lastMonday = new Date(beforeOneWeek.setDate(diffToMonday))
  , lastSunday = new Date(beforeOneWeek.setDate(diffToMonday + 6));

$( "#dateDebut" ).val($.datepicker.formatDate('dd/mm/yy', lastMonday));
$( "#dateFin" ).val($.datepicker.formatDate('dd/mm/yy', lastSunday));
user2733521
  • 439
  • 5
  • 22

2 Answers2

6

You have to clone beforeOneWeek. Everything else looks fin in your code

var beforeOneWeek = new Date(new Date().getTime() - 60 * 60 * 24 * 7 * 1000)
var beforeOneWeek2 = new Date(beforeOneWeek);
  day = beforeOneWeek.getDay()
  diffToMonday = beforeOneWeek.getDate() - day + (day === 0 ? -6 : 1)
  lastMonday = new Date(beforeOneWeek.setDate(diffToMonday))
  lastSunday = new Date(beforeOneWeek2.setDate(diffToMonday + 6));

$( "#dateDebut" ).val($.datepicker.formatDate('dd/mm/yy', lastMonday));
$( "#dateFin" ).val($.datepicker.formatDate('dd/mm/yy', lastSunday));
drkunibar
  • 1,327
  • 1
  • 7
  • 7
  • this works as well with weeks that span over different years, right? Or are there any problems if the last week of a year also has some days in the next year? – linus_hologram Oct 16 '20 at 11:38
  • This works also over different years. `beforeOneWeek` is calculated using Milliseconds, therefore days, months and years are irrelevant. – drkunibar Oct 16 '20 at 22:19
0

Here is the code:

var _now = new Date();

// get sunday by subtraction current week day from month day
var sunday = new Date(_now.setDate(_now.getDate() - _now.getDay()));
// get monday by subtraction 6 days from sunday
var monday = new Date(_now.setDate(_now.getDate() - 6));
var isDifferentMonth = sunday.getMonth() !== monday.getMonth();

See more about Date functions here.

Kiril
  • 2,935
  • 1
  • 33
  • 41