This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Following code snippet i got from here, I use to explain my problem.
1. Date d = new Date(); 2. System.out.println(d); 3. Calendar cal = new GregorianCalendar(); 4. cal.setTime(d); 5. cal.roll(Calendar.HOUR_OF_DAY, -1); // problem is here 6. d = cal.getTime(); 7. System.out.println(d);
lets say, in line no 2 printed as "Wed Feb 21 19:23:58 IST 2007" & line 6 printed "Wed Feb 21 18:26:15 IST 2007" if i pass 20 instead of 1 in line no 5, I'm getting "Wed Feb 21 23:27:16 IST 2007"
This is not what i need, i should get something like "Wed Feb 20 ......"
Adds a signed amount to the specified calendar field without changing larger fields. A negative roll amount means to subtract from field without changing larger fields. If the specified amount is 0, this method performs nothing.
So from that description, rolling -20 (not 20 as you say) to HOUR will change 12.34.56 21st February to 16.34.56 21st February.
Yes, it is difficult to understand; in fact a lot of people think Java's handling of dates is difficult to understand throughout.
Joined: Feb 21, 2007
Thanks for the early reply
Ok, I understand it. Do you have any suggetion for this. I mean any other alternatives
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Joined: Oct 13, 2005
You could try something like:- That won't work at all well if you try to roll 48 hours. I am not sure I have used the right terms for DAY or HOUR.
Joined: Oct 13, 2005
There may be other ways of rolling back.
Maybe:- You know the Calendar types are actually a timestamp which count milliseconds since 1st January 1970 at midnight. [It was actually 1.00am because we had summer time all winter that year.] Convert your Calendar object to milliseconds, convert your hour to milliseconds (3600000 of them), add the two values, and convert the milliseconds back. Not sure of the full details. You will have to see what you can find in the API.