• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

problem: How to get last month date

 
Peter Primrose
Ranch Hand
Posts: 755
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

quick question:
I have a date (Date, 2006-05-12) and i would like to get the same date last month: 2005-04-12.

right now I'm using:

int future= -30 ;

Calendar c = Calendar.getInstance();
c.setTime(someDay);
c.add(Calendar.DATE, future);

the problem is that a month can have 28,30,31 days, and as a result the previuos month will be incorrect.

any idea?
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Any solution would also have to account for the fact that the date might be the "31st", and many months don't have one of those.

In any case, the method Calendar.roll() does exactly what you want.
 
Paul Clapham
Sheriff
Pie
Posts: 20739
30
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And so does the method Calendar.add(), which you should use instead of roll() if you want to get December 2005 (not 2006) as the month before January 2006.
 
Peter Primrose
Ranch Hand
Posts: 755
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks for your reply but i don't think i fully understand it.

I am attaching a code sample, my question is how would you use the roll.
I read the sun documentation on the roll but could plug it in the code.

thanks


 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15206
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why don't you just subtract 1 month from the date instead of 30 days?
 
kittu vadde
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i think this will solve ur prob, if i understood correctly


[ May 16, 2006: Message edited by: kittu vadde ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic