tags:

views:

1427

answers:

3

Hi,

How to get last 30 / 60 / 90 days records from given date in java?

I have some records with receivedDate. I want to fetch the records for last 30 or 60 or 90 days from received Date. How to resolve it?

Thanks in advance

  • Gnaniyar Zubair
+3  A: 

Use java.util.Calendar.

Date today = new Date();
Calendar cal = new GregorianCalendar();
cal.setTime(today);
cal.add(Calendar.DAY_OF_MONTH, -30);
Date today30 = cal.getTime();
cal.add(Calendar.DAY_OF_MONTH, -30);
Date today60 = cal.getTime();
cal.add(Calendar.DAY_OF_MONTH, -30);
Date today90 = cal.getTime();
cletus
+1  A: 

not sure where you are fetching your data from but to compute the date that is say 30 days from now you can use the Calendar class's add function like so:

c.add(Calendar.DAY_OF_MONTH, -30); //assuming c is of type java.util.Calendar

Now to figure out if a particular date is between today and 30 days ago you can use the before() and after() functions to figure out if the date was before today but after the 30th day before today.

neesh
A: 

Honestly, I recommend you use Joda as your date&time library. Not only it has a superior API, but it understands (ie, has classes for) concepts like periods, duration and things like that.

Daniel