| Author |
problem: How to get last month date
|
Peter Primrose
Ranch Hand
Joined: Sep 10, 2004
Posts: 755
|
|
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
Joined: Jul 08, 2003
Posts: 24044
|
|
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.
|
[Jess in Action][AskingGoodQuestions]
|
 |
Paul Clapham
Bartender
Joined: Oct 14, 2005
Posts: 16482
|
|
|
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
Joined: Sep 10, 2004
Posts: 755
|
|
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
Bartender
Joined: Aug 16, 2005
Posts: 12907
|
|
Why don't you just subtract 1 month from the date instead of 30 days?
|
Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
|
 |
kittu vadde
Greenhorn
Joined: May 13, 2006
Posts: 27
|
|
i think this will solve ur prob, if i understood correctly [ May 16, 2006: Message edited by: kittu vadde ]
|
SCJP 1.4 <br />SCWCD 1.4 <br />SCBCD 'have start...
|
 |
 |
|
|
subject: problem: How to get last month date
|
|
|