Tuesday, 22 March 2016

How to minus months from the current date in java


Simple way to  subtract certain number of months from the current date is as follows


import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;


      SimpleDateFormat format = new SimpleDateFormat("dd MMMM yyyy");
      Calendar c = Calendar.getInstance();
      c.setTime(new Date());
      c.add(Calendar.MONTH, -1);
      Date d = c.getTime();
      String res = format.format(d);
     
Java 8 has the below feature of subtracting months

      Calendar c = Calendar.getInstance();
      LocalDateTime.from(c.toInstant()).minusMonths(1);

No comments:

Post a Comment