How to subtract X day from a Date object in Java ?

How to subtract X day from a Date object in Java ?

Asked on December 20, 2018 in Java.
Add Comment


  • 5 Answer(s)

    In Java 8 and later versions:

    Use LocalDate with Java 8’s date time API change, like this

    LocalDate date = LocalDate.now().minusDays(300);
    

    Here is Java 7 and earlier versions:
    Use Calender’s add() method

    Calendar cal = Calendar.getInstance();
    cal.setTime(dateInstance);
    cal.add(Calendar.DATE, -30);
    Date dateBefore30Days = cal.getTime();
    
    Answered on December 20, 2018.
    Add Comment

    Try to use joda-time:

    The need is add more possibilities to subtract days from a java.util.Date.

    In Apache-commons :
    Anyone can do it using DateUtils like this,

    Date dateBefore30Days = DateUtils.addDays(new Date(),-30);
    

    If we are already using commons-lang it’s a good one. There is also suited methods to addYears,addMonths,addWeeks and so on.

    For more reference in API.

    In Java 8 :
    To take advantage of new LocalDate from Java 8 using minusDays means long days method is possible:

    LocalDate dateBefore30Days = LocalDate.now(ZoneId.of("Europe/Paris")).minusDays(30);
    
    Answered on December 20, 2018.
    Add Comment

    We can use this solution, with the help of java 8 API,

    Instant now = Instant.now(); //current date
    Instant before = now.minus(Duration.ofDays(300));
    Date dateBefore = Date.from(before);
    
    Answered on December 20, 2018.
    Add Comment

    Java 8 Time API:

    Instant now = Instant.now(); //current date
    Instant before = now.minus(Duration.ofDays(300));
    Date dateBefore = Date.from(before);
    Answered on January 16, 2019.
    Add Comment

    You can easily subtract with calendar with SimpleDateFormat

     public static String subtractDate(String time,int subtractDay) throws ParseException {
    
    
            Calendar cal = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ENGLISH);
            cal.setTime(sdf.parse(time));
            cal.add(Calendar.DATE,-subtractDay);
            String wantedDate = sdf.format(cal.getTime());
    
            Log.d("tag",wantedDate);
            return wantedDate;
    
        }
    Answered on January 16, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.