Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript get first and last day of the previous week [duplicate]

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));
like image 647
user2733521 Avatar asked Oct 21 '22 10:10

user2733521


1 Answers

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));
like image 148
drkunibar Avatar answered Oct 29 '22 14:10

drkunibar