我希望在javascript中获得前一周的第一天(星期一)和最后一天(星期日)。我已经检查了其他主题,但它不起作用。如果前一周是2个不同的月份,我还需要处理。
我使用此代码,但是lastsunday是06/03/2014而不是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));
答案 0 :(得分:2)
您必须克隆beforeOneWeek
。其他一切看起来都在你的代码中
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));
答案 1 :(得分:0)
以下是代码:
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();
详细了解日期函数here。