Link to home
Start Free TrialLog in
Avatar of Westside2004
Westside2004Flag for United States of America

asked on

Dates and Military time validation needed

Hi,

I have two fields with dates and times in the format:

03/20/2006 16:07 (military times)

I need to ensure the following

That field 1 cannot be more than one day earlier than field 2.

How can I do this using JavaScript?

Thx

-ws
Avatar of SirCrofty
SirCrofty
Flag of United States of America image

Where elem1 is the id of the first date/time field and and elem2 is the id of second date/time field. Should return true if the difference between the two dates is greater than a day by even a couple minutes.

function showDateDiff(elem1, elem2)
{
     var d1 = new Date(Date.parse(document.getElementById(elem1).value));
     var d2 = new Date(Date.parse(document.getElementById(elem2).value));
     var diff = (d1-d2)/86400000;

     if (Math.abs(diff) > 1) alert("true");
}
ASKER CERTIFIED SOLUTION
Avatar of Michel Plungjan
Michel Plungjan
Flag of Denmark image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of el_dios
el_dios

I think this would be simpler:

var d1= //field1
var d2= //field2

var temp = new Date(d1);
temp.setDate(d1.getDate()+1);
if(temp>d2) return false;
Yes it would - if you made a date of d2 too.

More way to skin a cat:

aDay = 86400000;
function isMoreThanADay(strDate1,strDate2) {
  var d1 = new Date(strDate1).getTime();
  var d2 = new Date(strDate2).getTime();
  return (d2-d1)>aDay
}
function validate(theForm) {
  if (isMoreThanADay(theForm.date1.value,theForm.date2.value) ) {
.
.