在javascript中获取一周的日期

时间:2016-12-13 09:39:15

标签: javascript date

我想使用JavaScript获取本周的第一天和最后一天。

例如,今天是2016-13-12。

FD = 2016-11-12 LD = 2016-17-12

我如何获得FD和LD?我尝试使用此代码,

Date.prototype.GetFirstDayOfWeek = function() {
        return (new Date(this.setDate(this.getDate() - this.getDay())));
    }

    Date.prototype.GetLastDayOfWeek = function() {
        return (new Date(this.setDate(this.getDate() - this.getDay() +6)));
    }
    var today = new Date();

它正在工作,但我想在" 2016-12-11"中进行格式化。 此外,我还想将日期更改为过去或将来。 例如,如果我单击按钮"<"它将过去1周。然后,如果用户再次单击该按钮,它将在下一周获得。等等。

方案: DAtes现在是2016-11-12 - 2016-17-12 当用户点击按钮"<"。它将成为2016-04-12 - 2016-10-12

2 个答案:

答案 0 :(得分:1)

您可以使用下面的脚本查找当周的firstDay和lastDay;

//0=Sunday, 1=Monday
var d = new Date(); 
var day = d.getDay();

var firstDayOW = d.getDate() - day + (day == 0 ? -6:1); 
firstDay = new Date(d.setDate(firstDay));

var lastDayOW = firstDay + 6; 
lastDayOW = new Date(d.setDate(lastDayOW));

我希望这会对你有所帮助。

亲切的问候。

答案 1 :(得分: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

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