File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
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

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.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

Joined: Jul 08, 2003
Posts: 24199

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

Joined: Oct 14, 2005
Posts: 19973

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.


Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15101

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 8 API documentation
kittu vadde

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...
I agree. Here's the link:
subject: problem: How to get last month date
jQuery in Action, 3rd edition