Click to See Complete Forum and Search --> : Mathematical functions for mm/dd/yyyy
serecyn
11-10-2003, 08:05 AM
I was curious if there were any Javascript functions that would allow mathematical operations on a date, say in mm/dd/yyyy format, or, if anyone knows of any scripts out there that would do such a thing. I want to be able to subtract two date values from a form and get the number of days. For example, (10/31/2003 - 11/01/2002) = 364 days. I wasn't sure if there was any easy way to do this. Thanks!
olerag
11-10-2003, 08:17 AM
Overkill from an O'Reilly JS text...
function daysBetween(date1,date2) {
var DSTAdjust = 0;
var oneMinute = 1000 * 60;
var oneDay = oneMinute * 60 * 24;
date1.setHours(0);
date1.setMinutes(0);
date1.setSeconds(0);
date2.setHours(0);
date2.setMinutes(0);
date2.setSeconds(0);
if (date2 > date1) {
DSTAdjust = (date2.getTimezoneOffset() - date1.getTimezoneOffset()) * oneMinute;
}
else {
DSTAdjust = (date1.getTimezoneOffset() - date2.getTimezoneOffset()) * oneMinute;
}
var diff = Math.abs(date2.getTime() - date1.getTime()) - DSTAdjust;
return(Math.ceil(diff/oneDay);
}
olerag
11-10-2003, 08:22 AM
Bad syntax in "return" line.. should be...
return(Math.ceil(diff/oneDay));
serecyn
11-10-2003, 09:08 AM
When passing the values for date1 and date2, is there a specific format that each should be in? Can I use mm/dd/yyyy or does it need to be in the format produced by date()?
serecyn
11-10-2003, 10:12 AM
Nevermind... got it... Thanks for all your help! Much appreciated...
olerag
11-10-2003, 10:16 AM
I'd use the later (pass YYYY/MM/DD format to match Date()
constructor.
Note there's another thread near yours trying to format a
specialty Date() object for dd/mon/yyyy format wherein the
"mon" is the 3-char month abbreviation. Haven't seen a
response yet on this but would be interested.
For HTML I've typically placed month info in a single selection
list. Dates in JS can get messy.
serecyn
11-10-2003, 11:18 AM
Yup, I just created a form with a few select lists. The form button just calls the function below:
function calcdate()
{
day1 = document.calcdates.day1.value;
month1 = document.calcdates.month1.value;
year1 = document.calcdates.year1.value;
day2 = document.calcdates.day2.value;
month2 = document.calcdates.month2.value;
year2 = document.calcdates.year2.value;
// note: month is 0-11, not 1-12.
d1 = new Date(year1, month1, day1);
d2 = new Date(year2, month2, day2);
theDays = daysBetween(d1,d2);
document.write("Days: " + theDays);
}
Thanks again!