2

我有用于增加和减少周数的按钮。我必须显示本周的开始日期和结束日期。当我单击增量按钮时,必须显示下一周的开始日期和结束日期。如果我再次单击下一个开始日期和之后一周的结束日期,则必须显示。减量按钮也是如此。

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);
        }
    })

我将以这种格式显示日期 - Sep 15 2013-Sep 21 2013

本月代码运行良好,之后无法正常运行。请帮我解决这个问题。

4

2 回答 2

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();
});
于 2013-09-06T14:16:59.340 回答
0

罪魁祸首是var curr = new Date;

一旦超出月份边界(即 30 天以上),就会弄乱日期计算

如果var curr = new Date; 每次计算日期都取一个新的,问题就会迎刃而解。

见工作小提琴

于 2013-09-06T13:33:04.200 回答