File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

getting a Date that is 30 days ago from today

 
kay lin
Ranch Hand
Posts: 132
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 10336
Eclipse IDE Hibernate Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
kay lin
Ranch Hand
Posts: 132
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3340
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic