How do I get the date of 31 days ago?

Hi,

I have a requirement of creating a Capacity report for Last 1 week and Last 1 month.

I am using the below new Date() to achieve my weekly report. Which works :)

--> new Date(System.currentTimeMillis()-(7*1000*60*60*24))

---------> Function expansion goes as below,

--new Date(System.currentTimeMillis()-(No.of days * Milliseconds *Seconds * Minutes * Hours))

But while i use the same format as below for my monthly report. I am not getting the desired date (which should be 31 days from current date)

--> new Date(System.currentTimeMillis()-(31*1000*60*60*24))

Kindly suggest me a solution for the same.

Regards,

Venith

connect2venith's picture
Joined: Nov 30 2015 - 6:18am
Last seen: 1 year 5 months ago

Thanks guys (waynerod10 and hozawa ), it works :)

But what if I dont want to create a new parameter and use them directly on the ireport design page.
 
Eg:
Using the below new date function directly in ireports design page, will return the date of last week.
new Date(System.currentTimeMillis()-(7*1000*60*60*24)) 
 
Regards,
Venith
connect2venith - 6 years 9 months ago

2 Answers:

You'll know the reason why you're not getting the correct date if you just print out the result of 31*1000*60*60*24 - it's a negative value because of the overflow.

Try the following:

Date date = new Date(System.currentTimeMillis() - (31L * 1000L * 60L * 60L * 24L));

hozawa's picture
163159
Joined: Apr 24 2010 - 4:31pm
Last seen: 3 years 7 months ago

Hi,

I was struggling with a similar problem recently as well. I found that using java.util.Calendar instead of date is a better solution rather than doing the subtracting (unless you want exactly 31 days prior).

Create a variable/parameter for the Calendar object. I will call this "cal". Set the Class as "java.util.Calendar" and the Default value as "java.util.Calendar.getInstance()"

---

If you are using iReport, you can follow the below steps:

Create another parameter/variable for today's date. I will call it runDate which the Default value is "new Date()"

Then use the following for your

(   $P{cal}.set($P{runDate}.getYear()+1900, $P{runDate}.getMonth(), $P{runDate}.getDate()) ||    $P{cal}.add(Calendar.MONTH, -1))? null : $P{cal}.getTime()

Note: The $P dentoes that it is a parameter.

Suppose today is 26-02-2016, it will give you 26-01-2016.

Hope that helps. If you are not using iReport, happy to try and explain it using simple Java notation instead.

waynerod10's picture
Joined: Dec 3 2015 - 7:42pm
Last seen: 4 years 8 months ago
Feedback
randomness