How do I calculate today's date minus one month?

L

laredotornado

Hi,

I'm using Java 1.5. How do I get a java.util.Date exactly one month
before today's date? I thought about converting todays date to
milliseconds and then subtracting a value, but not every month has the
same number of milliseconds.

- Dave
 
J

Joshua Cranmer

laredotornado said:
Hi,

I'm using Java 1.5. How do I get a java.util.Date exactly one month
before today's date? I thought about converting todays date to
milliseconds and then subtracting a value, but not every month has the
same number of milliseconds.

Month as in "30 days" or "this day in the last calendar month"? What is
exactly one month before December 31? March 29?

Here's some code using Calendar that treats the equivalent of "November
31" as "November 30":

Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MONTH, -1);
date = cal.getTime();
 
T

Tim Slattery

laredotornado said:
Hi,

I'm using Java 1.5. How do I get a java.util.Date exactly one month
before today's date? I thought about converting todays date to
milliseconds and then subtracting a value, but not every month has the
same number of milliseconds.

Look at the add method of GregorianCalendar, that will do what you
need.
 
L

laredotornado

Look at the add method of GregorianCalendar, that will do what you
need.

What I meant by exactly one month is if today is "10-3-2008", one
month ago was "9-3-2008". Of course, I don't know what one month ago
means for "7-31-2008". But I have used GregorianCalendar's add
method, per Tim's suggestion

this.m_throughDate = new Date();
GregorianCalendar gc = new
GregorianCalendar(this.m_throughDate.getYear(),
this.m_throughDate.getMonth(), this.m_throughDate.getDate());
gc.add(Calendar.MONTH, -1);
this.m_fromDate = gc.getTime();

Thanks, - Dave
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,053
Latest member
billing-software

Latest Threads

Top