Hi, can some one suggest a way to compare values of 2 dates greater then, less then and not in the passed using javascript. They values will be coming from text boxes
Thanks
Hi, can some one suggest a way to compare values of 2 dates greater then, less then and not in the passed using javascript. They values will be coming from text boxes
Thanks
var date = new Date();
will give you todays date.
setDate()
setFullYear()
setHours()
setMilliseconds()
setMinutes()
setMonth()
setSeconds()
setTime()
will let you set new dates.
var yesterday = new Date(); yesterday.setDate(...date info here);
if(date>yesterday) will compare dates
what format?
If you construct a Javascript Date object, you can just subtract them to get a milliseconds difference (edit: or just compare them) :
js>t1 = new Date()
Thu Jan 29 2009 14:19:28 GMT-0500 (Eastern Standard Time)
js>t2 = new Date()
Thu Jan 29 2009 14:19:31 GMT-0500 (Eastern Standard Time)
js>t2-t1
2672
js>t3 = new Date('2009 Jan 1')
Thu Jan 01 2009 00:00:00 GMT-0500 (Eastern Standard Time)
js>t1-t3
2470768442
js>t1>t3
true
The Date object will do what you want - construct one for each date, then just compare them using the usual operators.
I suggest you use drop-downs or some similar constrained form of date entry rather than text boxes, though, lest you find yourself in input validation hell.
In order to create dates from free text in Javascript you need to parse it into the Date() object.
You could use Date.parse() which takes free text tries to convert it into a new date but if you have control over the page I would recommend using HTML select boxes instead or a date picker such as the YUI calendar control or the jQuery UI Datepicker.
Once you have a date as other people have pointed out you can use simple arithmetic to subtract the dates and convert it back into a number of days by dividing the number (in seconds) by the number of seconds in a day (60*60*24 = 86400).
The easiest way to compare dates in javascript is to first convert it to a Date object and then compare these date-objects.
Below you find an object with three functions:
dates.compare(a,b)
Returns a number:
dates.inRange (d,start,end)
Returns a boolean or NaN:
dates.convert
Used by the other functions to convert their input to a date object. The input can be
.
var dates = {
convert:function(d) {
return (
d.constructor === Date ? d :
d.constructor === Array ? new Date(d[0],d[1],d[2]) :
d.constructor === Number ? new Date(d) :
d.constructor === String ? new Date(d) :
typeof d === "object" ? new Date(d.year,d.month,d.date) :
NaN
);
},
compare:function(a,b) {
return (
isFinite(a=this.convert(a).valueOf()) &&
isFinite(b=this.convert(b).valueOf()) ?
(a>b)-(a<b) :
NaN
);
},
inRange:function(d,start,end) {
return (
isFinite(d=this.convert(d).valueOf()) &&
isFinite(start=this.convert(start).valueOf()) &&
isFinite(end=this.convert(end).valueOf()) ?
start <= d && d <= end :
NaN
);
}
}