How to get a date six months before the current date in one line in Java?

I want to get the date six months before the current date. The code I tried:

SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
Calendar c = Calendar.getInstance();
c.add(Calendar.MONTH, -6);
System.out.println(format.format(c.getTime()));

But I want to reduce this to a single row expression, which I want to use in my Jasper report to put a parameter expression.

How can I reduce it to a single line expression?

+4
source share
4 answers

wrap this util method in a Utility class, create a jar and put it in the classpath of your iReport and whenever you compile this jrxml

+4
source

Using Java 8, you can do this on one line:

System.out.println(LocalDate.now().minusMonths(6).format(DateTimeFormatter.ofPattern("yyyy/MM/dd")));

If you cannot use Java 8, use the Joda Time library .

+5
source

Joda - Date Calendar

new DateTime().minusMonths(6).toDate();

Java 8 .

LocalDateTime.from(referenceDate.toInstant()).minusMonths(6);
+1
source

To calculate the previous date, just do something like below, where the total number of previous days is multiplied by24 * 60 * 60 * 1000

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

Where, 7 days are deducted from the current date.

Calculate the number of days on the service side and pass it as a parameter to the next line of code to get the required previous date.

Hope this helps.

+1
source

All Articles