File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes problem: How to get last month date Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "problem: How to get last month date" Watch "problem: How to get last month date" New topic
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: 24183
    
  34

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: 18541
    
    8

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
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14108
    
  16

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...
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: problem: How to get last month date