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 Rhinorhino on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Comparing dates without time

Status
Not open for further replies.

jsulman

Programmer
Joined
Jun 14, 2001
Messages
85
Location
US
How do i compare dates irrespective of time? For example if I want to see if the dates are equal I cannot do it because when I get the current date it always gives me the time with it. So if I have a date 04/21/2004 00:00:00 from a form it is not equall to 04/21/2004 04:22:05 that I get from new Date(). How do I strip the date from them and ignore the time?

Thank you in advance

Jeff
 
You can build an integer of the fashion YYYYMMDD. The greater value is the later date.

Here's an example:

Code:
<html>
<head>
<script>
var date1 = new Date("4/1/2004");
var year1 = date1.getFullYear();
var month1 = date1.getMonth();
if(month1 < 10)
  month1 = "0" + month1;
var day1 = date1.getDate();
if(day1 < 10)
  day1 = "0" + day1;
var int1 = "" + year1 + month1 + day1;

function compareDates()
{
 var date2 = new Date();
 var year2 = date2.getFullYear();
 var month2 = date2.getMonth();
 if(month2 < 10)
  month2 = "0" + month2;
 var day2 = date2.getDate();
 if(day2 < 10)
  day2 = "0" + day2;
 var int2 = "" + year2 + month2 + day2;

 if(int1 < int2)
  alert("Fixed date is before today.");
 else if(int2 < int1)
  alert("Fixed date is after today.");
 else
  alert("Fixed date is today.");
}//end compareDates()
</script>
</head>
<body>
fixed date: 
<script>
document.write((date1.getMonth()+1) + "/" + date1.getDate() + "/" + date1.getFullYear());
</script>
<br />
compare date: today.<br />
<input type='button' value='compare' onclick='compareDates()' />
</body>
</html>

Be careful to use getDate() and not getDay() for the day of the month. Also notice that if the day (or month) is less than 10, a place-holding zero is added.

'hope this helps.

--Dave
 

Something like this should work for you:

Code:
	function checkDates(d1, m1, y1, d2, m2, y2) {
		var date1Time = new Date(y1, m1, d1).getTime();
		var date2Time = new Date(y2, m2, d2).getTime();
		if (date1Time < date2Time) {
			alert('Date 1 is earlier than date 2');
		} else if (date1Time > date2Time) {
			alert('Date 1 is later than date 2');
		} else {
			alert('Date 1 and date 2 are the same');
		}
	}

Hope this helps,
Dan
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top