2016-12-13 69 views
0

我希望在本周使用JavaScript的第一天和最后一天。在javascript中获取本周的日期

例如,今天是2016年12月12日。

FD =二〇一六年十一月一十二日 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周。那么如果用户再次点击该按钮,它将在下一周获得。等等。

情景:现在 日期是2016年11月12日 - 2016-17-12 当用户点击按钮 “<”。它会变成2016-04-12 - 2016-10-12

+0

你打算使用插件吗? MomentJS可以完成所有这一切。 http://momentjs.com/docs/特别为您的要求检查http://momentjs.com/docs/#/manipulating/start-of/,http://momentjs.com/docs/#/manipulating/end -of /,http://momentjs.com/docs/#/displaying/format/,http://momentjs.com/docs/#/manipulating/add/,http://momentjs.com/docs/#/操纵/减法/ – ADyson

+0

我不打算使用任何插件。不管怎么说,还是要谢谢你。 – JMA

+0

我可以问为什么不呢?这会为你节省很多努力。当然,除非你是在做这个学习练习。 – ADyson

回答

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

我希望这可以帮助你。

亲切的问候。

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(); 
相关问题