Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get date six month before current date in single line in Java?

I want to get a date six month before from present date. The code that I tried is:

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 line expression which I want to use in my Jasper report to put in parameter expression.

How can I reduce it to single line expression?

like image 440
Madhusudan Avatar asked May 05 '15 05:05

Madhusudan


1 Answers

Using Java 8 you can do this in single line:

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

If you cannot use Java 8 consider using Joda Time library.

like image 177
Tagir Valeev Avatar answered Sep 30 '22 00:09

Tagir Valeev