Search code examples
javascriptangulardateutc

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


I have try to get dates list between two date using JavaScript (I have already achieved in GMT).

Example:

fromDate - 2019-08-27

toDate - 2019-08-30

Date list

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

I have already got this array using this following 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);
        }
    });
}

The above JavaScript is working for only GTM and localtime(India). When I try to run this script in USA the date list array like this

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

Because of UTC not accept this script.

My question is how to solve this above script in UTC


Solution

  • 2019-08-27 is parsed as UTC, but getDate and setDate are local. The USA is west of Greenwich, so new Date('2019-08-27') produces a local date for 2019-08-26, adding a day makes it 2019-08-27.

    The same thing will happen for any timezone that has a negative offset.

    A simple fix is to use all UTC, e.g.:

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

    However, I'd advise explicitly parsing the date and not to use the built–in parser. A simple parse function is 2 or 3 lines of code, or you can use one of many parsing and formatting libraries.