我有这个代码获取当前日期,然后获得一周中的日期。 有时这段代码不起作用,例如,今天是08/15,我将获得08/13。 我还需要一个函数来获取一周的前一天和下一天。
var self = this;
var curr = new Date;
self.mult = 0;
self.firstDate = new Date;
self.lastDate = new Date;
var first = curr.getDate() - (curr.getDay()-1);
var last = first + 6;
self.firstDate(Utils.dateFormat(new Date(curr.setDate(first)),"%Y-%m-%d", true));
self.lastDate(Utils.dateFormat(new Date(curr.setDate(last)),"%Y-%m-%d", true));
这是查看本周前几天的功能,
var self= this;
var curr = new Date;
self.mult(self.mult()-7);
var first = curr.getDate() - (curr.getDay()-1) + self.mult();
var last = first + 5;
if(self.mult() <= 0){
last = last + 1;
}
self.firstDate(Utils.dateFormat(new Date(curr.setDate(first)),"%Y-%m-%d", true));
self.lastDate(Utils.dateFormat(new Date(curr.setDate(last)),"%Y-%m-%d", true));
这是查看本周下一天的功能,
var self= this;
var curr = new Date;
self.mult(self.mult()+7);
var first = curr.getDate() - (curr.getDay()-1) + self.mult();
var last = first + 5;
self.firstDate(Utils.dateFormat(new Date(curr.setDate(first)),"%Y-%m-%d", true));
self.lastDate(Utils.dateFormat(new Date(curr.setDate(last)),"%Y-%m-%d", true));
我不确定,但我认为只有前几天是问题所在。
以下是一个示例情况。
场景1: 用户访问页面,今天是09/15 那么firstDate必须是09/12然后lastDate必须是09/18 用户单击下一步,则firstDate必须为09/19,lastDate为09/25 用户再次单击下一步,则firstDate为09/26,lastDate为10/02 用户单击“上一个”,则firstDate必须为09/19,lastDate为09/25
场景2: 用户访问页面,今天是09/15 那么firstDate必须是09/12然后lastDate必须是09/18 用户单击“上一个”,则firstDate必须为09/5,lastDate为09/11 用户再次单击“上一个”,则firstDate必须为08/29,lastDate为09/4 用户单击下一步,则firstDate必须为09/5,lastDate为09/11
有人可以回答可以执行我的方案的代码吗?
答案 0 :(得分:0)
您可以使用setDate()
例如:
var a = new Date();
console.log(a)
//Thu Sep 15 2016 10:22:25 GMT+0200 (CEST)
a.setDate(a.getDate()+1);
console.log(a)
//Fri Sep 16 2016 10:22:25 GMT+0200 (CEST)
答案 1 :(得分:0)
我建议使用库来完成这样的任务。例如moment.js。
从现在开始的一周
moment(new Date()).startOf('isoWeek').format('MMMM Do YYYY, h:mm:ss ')
从现在开始的一周结束
moment(new Date()).endOf('isoWeek').format('MMMM Do YYYY, h:mm:ss ')
有关详细信息,请参阅: http://momentjs.com/