Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Date Difference 1

Status
Not open for further replies.

TMRO

Technical User
Jan 10, 2003
140
CA
Hi,

I have 2 textboxes which are holding different dates. I would like when I submit the page, to make sure that the difference between the 2 dates is not bigger than 60 days.

Can this be accomplished in Javascript?

Thanks a lot,
TMRO
 
here's an test example of what you're looking for:
Code:
<html>
<head>
<script language=javascript>

function dateCompare(date1, date2) {
   date1 = new Date(Date.parse(date1)).getTime();
   date2 = new Date(Date.parse(date2)).getTime();
   datediff = ((date1 - date2) < 0) ? (date2 - date1) : (date1 - date2);
   if (datediff > 5184000000) {
      alert("dates are greater than 60 days apart");
   }
   else {
      alert("dates are less than 60 days apart");
   }
}

</script>
</head>
<body>
<form name=blahForm>
<input type=text name=date1>date1<br>
<input type=text name=date2>date2<br>
<input type=button value='compare dates' onclick='dateCompare(blahForm.date1.value, blahForm.date2.value)'>
</form>
</body>
</html>

-kaht

banghead.gif
 

Not being one to turn down a chance to introduce people to methods they may not have used before (learning new stuff is always fun!), here's an alternative way of doing the following:

Code:
datediff = ((date1 - date2) < 0) ? (date2 - date1) : (date1 - date2);

It could be replaced with this:

Code:
datediff = Math.abs(date1 - date2);

Math.abs effectively removes any negative sign in front of the number, giving you the absolute value. This means that regardless of whether date1 is smaller or bigger than date2, the result will always be a positive number.

Just another way of achieving the same result!

Dan
 
just a thought but if you ever turn these dates into a full date and time the single instruction (?? not at home right now) to produce a string like

"Wed Oct 20 15:16:59 UTC+0100 2004 "

can differ on browsers. Opera uses the full day and month word. My solution to avoid this instruction is in the code for this page

 
Thanks for the tip Dan. To be completely honest, it never even crossed my mind to use the abs method, which is sad considering that's exactly what I needed. I have just trained myself to use the ? operator for everything lately. Any time I write code that is presented with a "if blah then this or that" situation I always try to write it using the ? operator, especially when assigning a value to a variable (like above).

-kaht

banghead.gif
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top