如何增加和减少一周?

时间:2013-09-06 12:47:38

标签: javascript jquery

我有递增和递减周数的按钮。我必须显示当前周的开始日期和结束日期。单击增量按钮时,必须显示下周的开始日期和结束日期。如果我再次单击下一个开始数据,则必须显示该周的结束日期。同样适用于减量按钮。

var i = 0;
    var curr = new Date; // get current date
    var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
    var last = first + 6; // last day is the first day + 6
    $('#btnPrevWeek,#btnNextWeek').click(function () {

        if ($(this).is('#btnNext')) {
            first = first + 7;
            last = last + 7;

            var firstday = new Date(curr.setDate(first)).toUTCString();
            var lastday = new Date(curr.setDate(last)).toUTCString();

            var startDatePieces = firstday.split(/[\s,]+/);
            var endDatePieces = lastday.split(/[\s,]+/);

            var startDate = startDatePieces[2] + " " + startDatePieces[1] + " " + startDatePieces[3];
            var endDate = endDatePieces[2] + " " + endDatePieces[1] + " " + endDatePieces[3];
            $('#lblWeekStartDate').html(startDate);
            $('#lblWeekEndDate').html(endDate);
        }
        else {
            first = first - 7;
            last = last - 7;

            var firstday = new Date(curr.setDate(first)).toUTCString();
            var lastday = new Date(curr.setDate(last)).toUTCString();

            var startDatePieces = firstday.split(/[\s,]+/);
            var endDatePieces = lastday.split(/[\s,]+/);

            var startDate = startDatePieces[2] + " " + startDatePieces[1] + " " + startDatePieces[3];
            var endDate = endDatePieces[2] + " " + endDatePieces[1] + " " + endDatePieces[3];
            $('#lblWeekStartDate').html(startDate);
            $('#lblWeekEndDate').html(endDate);
        }
    })

我将以此格式显示日期 - 2013年9月15日 - 2013年9月21日

对于当前月份,代码工作正常,之后它无法正常工作。请帮助我解决问题。

2 个答案:

答案 0 :(得分:1)

只需使用日期值:

http://jsfiddle.net/k6jfR/

var week = 7 * 24 * 60 * 60 * 1000;

var curr = new Date();

var first = new Date();
    first.setDate(curr.getDate() - curr.getDay());

var last = new Date();
    last.setDate(first.getDate() + 6);

var parseDate = function(d){
  var datePieces = d.toUTCString().split(/[\s,]+/);
  return datePieces[2] + " " + datePieces[1] + " " + datePieces[3];
}
var printDates = function(){
  $('#lblWeekStartDate').html(parseDate(first));
  $('#lblWeekEndDate').html(parseDate(last));
}

printDates();

$('#btnNextWeek').click(function () {
  first = new Date(first.valueOf() + week);
  last = new Date(last.valueOf() + week);
  printDates();
});
$('#btnPrevWeek').click(function () {
  first = new Date(first.valueOf() - week);
  last = new Date(last.valueOf() - week);
  printDates();
});

答案 1 :(得分:0)

罪魁祸首是var curr = new Date;

一旦你离开月界,即超过30天

,它就会弄乱一天的计算

如果每次计算日期时都采用新的var curr = new Date;,问题就会得到解决。

见工作fiddle