Expand my Community achievements bar.

Calculating Days

Avatar

Community user
I have an end date and a start date. How do I get my form to calculate a total number of days by subtracting my start date from my end date.
12 Replies

Avatar

Community user
if you're using javascript:



>var oStart = new Date(DateTimeField1.formattedValue);



>var oEnd = new Date(DateTimeField2.formattedValue);



>this.rawValue = oEnd.getDate() - oStart.getDate();



paste the script into the calculate event of a text field to see it in action...

Avatar

Community user
Hi. I used this script to calculate the difference between the dates(one is to be filled in by the user and the other is today's date). I must be doing something wrong because it will only calculate correctly for the next 4 days (until the end of the month).



For example when I choose Feb. 28, 2009 it calculates it correctly as 4 days but when I choose March 1, 2009 it calculates that as -23. Clearly there are not negative 23 days between Feb. 24 2009 and March 1 2009. What am I doing wrong? Thank you!

Avatar

Community user
That script will not calculate the difference between to dates. If you post your email address I will send you a couple of date arithmetic samples that will show you how to deal with this.

Avatar

Level 7
Paul - Can you please send me a copy



aditya.shah@gsinc.com



Thanks !

Avatar

Level 2

Hi Paul. Would you please send me your document? Thanks! michael.murphy3@usdoj.gov

I assume that Steve's sample will do the trick for you.....if not let me know and I will post mine.

Paul

Avatar

Level 2

Thank you Steve, and thanks for the follow up Paul! I was looking for a Javascript solution since we decided to standardize on Javascript a while ago. I

googled around and found something similar to the following:

if

(!tripDateFrom.isNull && !tripDateTo.isNull)

{

var dateString, dateSplit, dateParse;

  dateString

= tripDateFrom.rawValue;

  dateSplit       = dateString.split("-");

  dateParse     = dateSplit[0] + "/" + dateSplit[1] + "/" + dateSplit[2];

var FromDate = Date.parse(dateParse);

  dateString     = tripDateTo.rawValue;

  dateSplit       = dateString.split("-");

  dateParse     = dateSplit[0] + "/" + dateSplit[1] + "/" + dateSplit[2];

  var ToDate     = Date.parse(dateParse);

  this.rawValue = Math.round((ToDate.valueOf()-FromDate.valueOf())/(1000*60*60*24));

  if (ToDate.valueOf() <= FromDate.valueOf())

  {

    xfa.host.messageBox("Your Trip Date From must occur before your Trip Date To.", "Date Error", 0, 0);

    this.rawValue = 0;

  }

}

This seems to work, even with month and year changes. I was hoping to replace a few statements in there with the String.split() method, but haven't tried yet. If you guys strongly recommend FormCalc, I'm happy to break our rule.