使用angular7以utc时间获取2个日期(fromDate和toDate)之间的日期列表

Get dates list between 2 dates (fromDate and toDate) in utc time using angular7

我尝试使用 JavaScript 获取两个日期之间的日期列表(我已经在 GMT 中实现)。

示例:

fromDate - 2019-08-27

toDate - 2019-08-30

日期列表

[2019-08-27, 2019-08-28, 2019-08-29, 2019-08-30]

我已经使用下面的这个得到了这个数组JavaScript

if(result.data.closurPeriods.length > 0) { 
    result.data.closurPeriods.forEach(closure => { 
        var start = closure.fromDate, //closure.fromDate = 2019-08-27
        end = new Date(closure.toDate), //closure.toDate = 2019-08-30
        currentDate = new Date(start);

        while (currentDate <= end) { 
            this.closurPeriods.push(this.datePipe.transform(new Date(currentDate), 'yyyy-MM-dd'));
            currentDate.setDate(currentDate.getDate() + 1);
        }
    });
}

以上 JavaScript 仅适用于 GTMlocaltime(印度)。当我尝试在 USA 日期列表数组中 运行 这个脚本时

[2019-08-28, 2019-08-28, 2019-08-29]

因为 UTC 不接受这个脚本。

My question is how to solve this above script in UTC

2019-08-27 被解析为 UTC,但 getDatesetDate 是本地的。美国位于格林威治以西,因此 new Date('2019-08-27') 生成本地日期 2019-08-26,加上一天使其成为 2019-08-27。

对于具有负偏移量的任何时区都会发生同样的事情。

一个简单的解决方法是使用所有 UTC,例如:

function fillRange(start, end) {
  let result = [start];
  let a = new Date(start);
  let b = new Date(end);
  while (a < b) {
    a.setUTCDate(a.getUTCDate() + 1);
    result.push(a.toISOString().substr(0,10));
  }
  return result;
}

let from = '2019-08-27';
let to = '2019-08-30';
console.log(fillRange(from, to));

但是,我建议明确解析日期而不是使用内置解析器。一个简单的解析函数是 2 或 3 行代码,或者您可以使用许多解析和格式化库之一。

终于找到解决方案

var start = new Date(closure.fromDate); // 2019-07-27
var end = new Date(closure.toDate); // 2019-07-31
var currentDate = start;

while (currentDate <= end) {
   //this.closurPeriods.push(this.datePipe.transform(new Date(currentDate), 'yyyy-MM-dd'));
   var date = new Date(currentDate);
   var datewithouttimezone = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());
   this.closurPeriods.push(this.datePipe.transform(new Date(datewithouttimezone), 'yyyy-MM-dd'));
   currentDate.setDate(currentDate.getDate() + 1);
}

var start = new Date(closure.fromDate); // 2019-07-27
var end = new Date(closure.toDate); // 2019-07-31
var currentDate = start;

while (start < end) {
       start.setUTCDate(start.getUTCDate() + 1);
       this.closurPeriods.push(start.toISOString().substr(0, 10));
    }