0

I have a while loop that selects dateCells inclusively that is now breaking due to daylight saving coming up and i'm wondering if there's a better way of fixing it.. (my plan is below the code)

function doLoop(startDateObj, endDateObj){
  console.log("start: " + startDateObj)
  console.log("end: " + endDateObj)
  console.log("-----")

  var counterDateObj = new Date(startDateObj);
  while (true){
    if (counterDateObj.getTime()>endDateObj.getTime()){
      // hit! reached after end date

      console.log("=> hit");
      console.log("counter: "+counterDateObj)
      console.log("getTime(): "+counterDateObj.getTime()+" > "+endDateObj.getTime())

      break;
    };

    console.log(counterDateObj);
    counterDateObj.setUTCDate(counterDateObj.getUTCDate() + 1);
  };
};

Putting values before and after daylight savings throws the entire thing off:

doLoop(new Date('03/07/09'), new Date('03/10/09'));

VM2826:2  start: Sat Mar 07 2009 00:00:00 GMT-0500 (Eastern Standard Time)
VM2826:3  end: Tue Mar 10 2009 00:00:00 GMT-0400 (Eastern Daylight Time)
VM2826:4  -----
VM2826:18 Sat Mar 07 2009 00:00:00 GMT-0500 (Eastern Standard Time)
VM2826:18 Sun Mar 08 2009 00:00:00 GMT-0500 (Eastern Standard Time)
VM2826:18 Mon Mar 09 2009 01:00:00 GMT-0400 (Eastern Daylight Time)
VM2826:11 => hit
VM2826:12 counter: Tue Mar 10 2009 01:00:00 GMT-0400 (Eastern Daylight Time)
VM2826:13 getTime(): 1236661200000 > 1236657600000

My current plan is: if it's greater than endDate timestamp + 5 extra hours in milliseconds, or something similar..

Can anyone think of a better way? My plan seems pretty ehhhh- not good

Nealium
  • 2,025
  • 1
  • 7
  • 9
  • imagine it didn't say 2009 but 2020 – Nealium Mar 04 '20 at 18:29
  • Could you please summarise what you require? – electrocrat Mar 04 '20 at 19:10
  • Just anything to get the loop working correctly ¯\_(ツ)_/¯ Basically it shouldn't break on the 10th but the 11th. Is there a better way to add a day that doesn't shift the hours to 01:00:00? Is there a better if statement (besides the getTime() ) for checking if it's the next day? – Nealium Mar 04 '20 at 19:39
  • You're mixing local and UTC date values, don't use UTC methods in `counterDateObj.setUTCDate(counterDateObj.getUTCDate() + 1)`. – RobG Mar 04 '20 at 20:18
  • **That was it!* so dumb.. I swear I changed it to UTC to deal with some other edge case but w/e. I appreciate it! (: – Nealium Mar 04 '20 at 22:30
  • In most cases, you should work only in one or the other, don't mix them unless you know exactly what you're doing. – RobG Mar 05 '20 at 02:09

0 Answers0