Expand my Community achievements bar.

## Day difference between two dates

Level 2

Hello,

my form contains a datetimefield in which a user can select any date.

Now I need to know how many days are between the entered date and the current system date.

Does anybody have an idea how the javascript can be look like?

Thanks a lot.

ra_be

2 Replies

Level 10

Hi ra_be,

Assuming your date fields are in the same format as your previous question you can use;

var

msPerDay = 86400000;

var

date1 = util.scand("d.mm.yy", DateTimeField1.formattedValue);

var

date2 = util.scand("d.mm.yy", DateTimeField2.formattedValue);

- date1.valueOf()) / msPerDay));

Bruce

Level 1

Here is some working JavaScript code from one of my forms that you might be able to adapt to your problem:

form1.#subform[0].TextFieldAge::calculate - (JavaScript, client)
// Given a Date/Time Field ("DateTimeFieldDOB") and a Text Field ("TextFieldAge")
// calculate TextFieldAge in years based on DateTimeFieldDOB and the current date
var strDateBirth = DateTimeFieldDOB.rawValue;  // Returns String in format "YYYY-MM-DD"
if ((strDateBirth != null) && (strDateBirth != ""))
{
// Change date format to "YYYY/MM/DD"
var strDateBirthSlash = strDateBirth.replace(/-/g, "/");

// Convert string to Date object
var dateBirth = new Date(strDateBirthSlash);
var dateToday = new Date();  // Get the current date

// Get difference between dates in milliseconds
var nAgeMilliseconds = dateToday.getTime() - dateBirth.getTime();

// Define number of milliseconds in one year
var nMilliSecondsPerYear = 365 * 24 * 60 * 60 * 1000;

// Get age in years (does not factor in leap years, but is close enough)
var nAgeYears = Math.floor(nAgeMilliseconds / nMilliSecondsPerYear);

TextFieldAge.rawValue = nAgeYears;
}