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
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));
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.
Thanks guys (waynerod10 and hozawa ), it works :)