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));
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With