CoffeePeddlerIntern
CoffeePeddlerIntern

Reputation: 679

Grails Date Contraints

Im trying to add constraints to a user submitted text field, which is there Date of Birth. I need the user to be at least 18 but cant be over 113 years old.

final static Date MIN_DATE = new Date(Calendar.YEAR-18)
final static Date MAX_DATE = new Date(Calendar.YEAR-100)

static constraints = {
    dob(nullabe: false, min: MIN_DATE, max: MAX_DATE
}

When I,

System.out.println('Year Max Date: ' + person.MAX_DATE)

it gives me,

Year Max Date: Wed Dec 31 17:59:59 CST 1969

and so does the min date.

I tried doing

final static Date MIN_DATE = new Date().getAt(Calendar.YEAR)-18

but that didn't work at all. I also tried doing it without the -18 and got the correct answer but it was 7 hours off. When I tried to relaunch the app from local it crashed it. And I cant recreate it ever since.

I have come to the understanding that the date its giving is the "Epoch" date or the date right before Unix was launched. Im just not sure how to get around it.

Any ideas/suggestions/concerns/experience with this problem? Any Help would be greatly appreciated.

Upvotes: 1

Views: 871

Answers (3)

tim_yates
tim_yates

Reputation: 171084

I don't agree with these constraints, firstly as they seem arbitrary (why should someone not be older than 100? And why can't I just lie if I am 16?)

And secondly, if the webserver is up for a couple of years, these static dates will slowly drift

But anyway (these concerns aside), I believe what you want is:

final static Date MIN_DATE = Calendar.instance.with { add( YEAR, -18 ) ; it }.time
final static Date MAX_DATE = Calendar.instance.with { add( YEAR, -100 ) ; it }.time

Upvotes: 2

opi
opi

Reputation: 244

You need to convert the user submitted text field (a String) to a Date object with SimpleDateFormat. Then create a Calendar with the Date object and check the Year field.

Alternatively you can just parse the text field (String) yourself and pick the year, convert to int and do the check.

Upvotes: 0

dan
dan

Reputation: 13272

The issue is that Date constructor expects an argument representing milliseconds since January 1, 1970, 00:00:00 GMT. Since Calendar.YEAR is a constant that is used to represent the year field from a Calendar structure and equal to 1 you are getting the above values.

Upvotes: 0

Related Questions