Skip to main content
Participant
March 14, 2023
Question

Date calculation screwed up by daylight saving time.

  • March 14, 2023
  • 1 reply
  • 838 views

I have a travel form which takes the start & end date for the travel which populates a date field for each day of the travel, which is then used for calculating per diem. When I select a date range before or after 3/12/2023 the form works just fine. However, when the date range includes 3/12/2023 it drops the last date of the range. After some testing I figured the micro time for the calculated date (step date) is off by 3599.999 seconds. This results in "if (step <= end)" being false for the last date of the range. I've included the calculation script for the step date below.

var s1 = this.getField("Expected Depart Date").valueAsString; //start date
var r1 = this.getField("Expected Return Date").valueAsString; //end date
var days = 1 * (24 * 60 * 60 * 1000); // calculates the number of days to add to s2

var s2 = util.scand("m/d/yyyy", s1);
s2 = s2.valueOf();
var r2 = util.scand("m/d/yyyy", r1);
r2 = r2.valueOf();
var b2 = s2 + days; //calculates the step date

if ((b2 <= r2) && (s1 != "")){ //if step date <= end date
    console.println("b2:" + b2);
    b2 = new Date(b2);
    event.value = util.printd("m/d/yyyy", b2);
} else { //if step date > end date, event value is blank
    console.println("b2:" + b2 + ", s2:" + s2 + ", r2:" + r2);
    event.value = "";
}
This topic has been closed for replies.

1 reply

try67
Community Expert
Community Expert
March 14, 2023

This happens to a lot of people who use milliseconds to add time to a Date object. Instead, you should be using the setDate method, like this:

 

var d1 = new Date();

d1.setDate(d1.getDate()+1);

 

This will set d1 to the next day from the current one.

Participant
March 14, 2023

Thank you. This got me to the solution. This is how I reworked the original code snipit from above.

var s1 = new Date(this.getField("Expected Depart Date").valueAsString);
var r1 = new Date(this.getField("Expected Return Date").valueAsString);
var days = 1;
var b1 = s1;
b1.setDate(b1.getDate() + days);

if ((b1 <= r1) && (s1 != "")){
    event.value = util.printd("m/d/yyyy", b1);
} else {
    event.value = "";
}