File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes Setting a cookie to expire at midnight Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "Setting a cookie to expire at midnight" Watch "Setting a cookie to expire at midnight" New topic

Setting a cookie to expire at midnight

Katie McCann
Ranch Hand

Joined: Jul 24, 2000
Posts: 45
I am writing a servlet that is supposed to set a cookie to expire at midnight on the day it was set. Not having used cookies in Java before (or time, for that matter), I am having trouble. Below is my code:
Cookie votingCookie = new Cookie ("voting", "voted");
Calendar now= new GregorianCalendar();
Calendar tonight= new GregorianCalendar();
Date time= new Date();
tonight.set(now.YEAR, now.MONTH, now.DATE, 24,00);
long nowSeconds= (now.HOUR_OF_DAY * 3600) + (now.MINUTE * 60);
long tonightSeconds= (tonight.HOUR_OF_DAY * 3600) + (tonight.MINUTE * 60);
System.out.println("Tonight Hour of Day= " + tonight.HOUR_OF_DAY);
System.out.println("Tonight Minute= " + tonight.MINUTE);
System.out.println("Now Hour of Day= " + now.HOUR_OF_DAY);
System.out.println("Now Minute= " + now.MINUTE);
System.out.println("Tonight Seconds= " + tonightSeconds);
System.out.println("Now Seconds= " + nowSeconds);
System.out.println("Num seconds= " + (tonightSeconds - nowSeconds) );
votingCookie.setMaxAge((int)(tonightSeconds - nowSeconds));

The standard output in the Jrun log is:
Tonight Hour of Day= 11
Tonight Minute= 12
Now Hour of Day= 11
Now Minute= 12
Tonight Seconds= 40320
Now Seconds= 40320
Num seconds= 0
In fact, I get an hour of 11 and a minute of 12 no matter when I run the servlet. Anyway, I'm stumped, and any help is greatly appreciated.
Paul Wetzel
Ranch Hand

Joined: Nov 02, 1999
Posts: 107
I think I have this figured out...The public static final int's that you use (such as tonight.HOUR_OF_DAY) are ints. They are used to get info from a GregorianCalendar object (gregCal.get(GregorianCalendar.HOUR_OF_DAY). whenever you see something like that in all capital letters you can pretty much count that it is a constant (or public static final). I think that the calls should look like this
hope this is correct
[This message has been edited by Paul Wetzel (edited November 17, 2000).]
Katie McCann
Ranch Hand

Joined: Jul 24, 2000
Posts: 45

Thanks! That solved it. I should have caught that.
I agree. Here's the link:
subject: Setting a cookie to expire at midnight
It's not a secret anymore!