views:

83

answers:

3

Hi,

I have created 3 select boxes containing days, months and year. What I really would like is to check after the user has selected a date, if the date is over a year from the current date a message is displayed or so.

Im a little stumped on what to do. Any gidance would be great.

Thanks

+1  A: 
var ddlYear = document.getElementById('ddlYear');
var ddlMonth = document.getElementById('ddlMonth');
var ddlDay = document.getElementById('ddlDay');

var y = ddlYear[ddlYear.selectedIndex];
var m = ddlMonth[ddlMonth.selectedIndex];
var d = ddlDay[ddlDay.selectedIndex];

// past
var dt = new Date((y+1), (m-1), d);
var moreThanOnYearAgo = dt < new Date();

// future
var dt2 = new Date((y-1), (m-1), d);
var moreThanOnYearAhead = dt2 > new Date();

The y+1 is because if we're adding one year, and are still less than new Date() (today), then it's more than one year ago.

The m-1 is because months in the Date constructor are an enum, which means January is 0.

David Hedlund
He asked for a year in the future, not in the past ;)
Justin Johnson
The only instructions we've got is "if the date is over a year from the current date", which i guess we can interpret in any direction...? but good catch; i edited my post to accommodate both
David Hedlund
A: 

There are 31556926000 milliseconds in a year. Just convert that date to a timestamp and subrtact the current date from it. If the result is greater than 31556926000 from it, is over a year away.

var userDate = new Date("11/29/2010");
var now      = new Date();
var year_ms  = 31556926000;

if ( userDate.getTime() - now.getTime() >= year_ms ) {
    // A year away
} else {
    // less than a year away
}
Justin Johnson
Why the down vote?
Justin Johnson
A: 

Don't reinvent the wheel one more time. Use a library that does validation.

Elzo Valugi
An existing library is usually the best option, but if the OP isn't already using jQuery, this is too much. Also, a little basic math doesn't really require a library/plugin
Justin Johnson
@justin I guess he should also do event binding? Furthermore I think most users allready have a cached version of Jquery from google CDN.
Alfred
validation is a thing that you do over and over in each form, on each website ... ok. do your own validation functions. Think in architecture not in scripts.
Elzo Valugi