从javascript开始和结束日期开始几周

我正在构建一个时间表函数,因为我必须在一个集合中将数据周插入.

所以我创建了一个数组,其中包含从start_date到end_date的周数.

第一次推入数组:start_date =声明日期(如果声明的日期是星期日,那么它考虑到星期一的日期); end_date =星期六的日期

第二个到第n个推入一个数组:start_date =星期一的日期; end_date =星期六的日期或声明的结束日期(如果它在一周内)

var start = new Date("09/30/2016");
var end = new Date("11/2/2016");

var count = 0;
var sDate;
var eDate;
var dateArr = [];

while(start <= end){
    if (start.getDay() == 0){
        count = 0;
    }else {
        if(count == 0){
            sDate = start;
            count = 1
        }else {
            count = 1;
        }

        if(start.getDay() == 6 || start == end){
            count = 1
            eDate = start;
        }else {
            count = 1;
        }

        if(sDate && eDate){
            sDate = new Date(sDate)
            eDate = new Date(eDate)
            dateArr.push({'startDate': sDate,'endDate': eDate});
            sDate = undefined;
            eDate = undefined;
        }
    }

    var newDate = start.setDate(start.getDate() + 1);
    start = new Date(newDate);
}

但我得到的结果就是这个

[{
    'startDate':Sat Oct 01 2016 00:00:00 GMT+0530 (IST),'endDate':Sat Oct 01 2016 00:00:00 GMT+0530 (IST),},{
    'startDate':Tue Oct 04 2016 00:00:00 GMT+0530 (IST),'endDate':Sat Oct 08 2016 00:00:00 GMT+0530 (IST),{
    'startDate':Tue Oct 11 2016 00:00:00 GMT+0530 (IST),'endDate':Sat Oct 15 2016 00:00:00 GMT+0530 (IST),{
    'startDate':Tue Oct 18 2016 00:00:00 GMT+0530 (IST),'endDate':Sat Oct 22 2016 00:00:00 GMT+0530 (IST),{
    'startDate':Tue Oct 25 2016 00:00:00 GMT+0530 (IST),'endDate':Sat Oct 29 2016 00:00:00 GMT+0530 (IST),}]

编辑:

预期结果:

[{
    'startDate':Fri Sep 30 2016 00:00:00 GMT+0530 (IST),{
    'startDate':Mon Oct 03 2016 00:00:00 GMT+0530 (IST),{
    'startDate':Mon Oct 10 2016 00:00:00 GMT+0530 (IST),{
    'startDate':Mon Oct 17 2016 00:00:00 GMT+0530 (IST),{
    'startDate':Mon Oct 24 2016 00:00:00 GMT+0530 (IST),{
    'startDate':Mon Oct 31 2016 00:00:00 GMT+0530 (IST)
    'endDate':Wed Nov 02 2016 00:00:00 GMT+0530 (IST),}]

解决方法

看一下这个.我修复了一些逻辑和obj引用错误.

var start = new Date(Date.UTC(2016,09,30,0));
var end = new Date(Date.UTC(2016,11,02,0));
var sDate;
var eDate;
var dateArr = [];

while(start <= end){
  if (start.getDay() == 1 || (dateArr.length == 0 && !sDate)){
    sDate = new Date(start.getTime());
  }

  if ((sDate && start.getDay() == 0) || start.getTime() == end.getTime()){
        eDate = new Date(start.getTime());
  }

  if(sDate && eDate){
    dateArr.push({'startDate': sDate,'endDate': eDate});
    sDate = undefined;
    eDate = undefined;
  }

    start.setDate(start.getDate() + 1);
}

console.log(dateArr);

https://jsfiddle.net/c58zde4b/6/

显示的日期可能因您当地的时区设置而异.

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...