| Author |
getting a Date that is 30 days ago from today
|
kay lin
Ranch Hand
Joined: May 20, 2004
Posts: 132
|
|
Hi All, I want to display a Date that is 30 days ago from today, and I used Date object here is my code, However, the display result is incorrect. i.e. The month value is incorrect, today is Jun 4, so 30 days ago, the month should be May (which is 4 numerically). can somebody tell me what i did wrong, or rather, let me know if I should use something different to get the date that is 30 days ago thanks
|
 |
Paul Sturrock
Bartender
Joined: Apr 14, 2004
Posts: 10336
|
|
|
I think you should have a look at the Calendar object and its roll(int field, int value) method, which you should find a little easier to use.
|
JavaRanch FAQ HowToAskQuestionsOnJavaRanch
|
 |
kay lin
Ranch Hand
Joined: May 20, 2004
Posts: 132
|
|
Originally posted by Paul Sturrock: I think you should have a look at the Calendar object and its roll(int field, int value) method, which you should find a little easier to use.
But the roll methods only takes care of the field you use, not the larger fields though. For example, if today is June 4, and I want it to be 30 days ago, then only the Day dispaly will be correct not the month, any other suggestions?
|
 |
Carl Trusiak
Sheriff
Joined: Jun 13, 2000
Posts: 3340
|
|
The simple answer is found if you do System.out.println(1000 * 60 * 60 * 24 * 30); Result -1702967296 You are overflowing an int, that why Date uses a long. Try Date from = new Date( to.getTime() - 1000L*60L*60L*24L*30L); Force these to a long! Of course the Calendar is a great suggestion
|
I Hope This Helps
Carl Trusiak, SCJP2, SCWCD
|
 |
Jim Yingst
Wanderer
Sheriff
Joined: Jan 30, 2000
Posts: 18670
|
|
|
You can also use Calendar's add() method rather than roll(), to make things simpler. And note that Date's getXXX() methods are deprecated. Better to use a SimpleDateFormat, or a Calendar, to extract this info from a Date. (Or use the Date's toString() method, which may be exactly what you want.)
|
"I'm not back." - Bill Harding, Twister
|
 |
 |
|
|
subject: getting a Date that is 30 days ago from today
|
|
|