aspose file tools*
The moose likes Beginning Java and the fly likes Date in java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Date in java" Watch "Date in java" New topic
Author

Date in java

vidhya subramaniam
Ranch Hand

Joined: Jul 14, 2001
Posts: 91
How can I get yesterday's date in java.
if i use
Date d = new Date() ---- its going to give me today's date.
I want to look into my program only for records from yesterday after 2 pm. how can i do that
thanks,
vidhya
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
You should use the GregorianCalendar class instead of the Date class. GregorianCalendar has a method named roll() which lets you easily change the date by any increment. You can also set the time to exactly 2:00 p.m. or whatever you wish.
HTH
Layne


Java API Documentation
The Java Tutorial
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Ack! You don't want to use roll() here - if the date is Jan 1, 2003 and you do
calendar.roll(Calendar.DATE, -1);
you will get Jan 31. Instead use add():
calendar.add(Calendar.DATE, -1);
This will get you to Dec 31, 2002 as expected.


"I'm not back." - Bill Harding, Twister
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
According to the API, GregorianCalendar doesn't have the same issues as its base class, Calendar. I just skimmed through it, though, so I may have misunderstood.
Layne
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
I'm not sure which part of the API you mean, but I think you misunderstood. Look carefully at the API for the roll(int, int) method, and compare it to the add(int, int) method.
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
Thank you for the correction. I guess I should be more specific. I read the following in the documentation for Calendar.roll(), but I didn't go to the GregorianCalendar API to see if it had any caveats documented there.
Time Field Rolling function. Add to field a signed amount without changing larger fields. A negative roll amount means to roll down. [NOTE: This default implementation on Calendar just repeatedly calls the version of roll() that takes a boolean and rolls by one unit. This may not always do the right thing. For example, if the DAY_OF_MONTH field is 31, rolling through February will leave it set to 28. The GregorianCalendar version of this function takes care of this problem. Other subclasses should also provide overrides of this function that do the right thing.

Mostly, it just looked like it might work, so I was trying to point the original poster in the direction that would (hopefully) answer his question. I should put disclaimers on such advice in the future.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Date in java