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

JavaDateDatetimeCalendarjava.util.date

Java Problem Overview


I want to do something like:

Date date = new Date(); // current date
date = date - 300; // substract 300 days from current date and I want to use this "date"

How to do it?

Java Solutions


Solution 1 - Java

Java 8 and later

With Java 8's date time API change, Use LocalDate

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

Similarly you can have

LocalDate date = someLocalDateInstance.minusDays(300);

Refer to https://stackoverflow.com/a/23885950/260990 for translation between java.util.Date <--> java.time.LocalDateTime

Date in = new Date();
LocalDateTime ldt = LocalDateTime.ofInstant(in.toInstant(), ZoneId.systemDefault());
Date out = Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());

Java 7 and earlier

Use Calendar's add() method

Calendar cal = Calendar.getInstance();
cal.setTime(dateInstance);
cal.add(Calendar.DATE, -30);
Date dateBefore30Days = cal.getTime();

Solution 2 - Java

@JigarJoshi it's the good answer, and of course also @Tim recommendation to use .joda-time.

I only want to add more possibilities to subtract days from a java.util.Date.

Apache-commons

One possibility is to use apache-commons-lang. You can do it using DateUtils as follows:

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

Of course add the commons-lang dependency to do only date subtract it's probably not a good options, however if you're already using commons-lang it's a good choice. There is also convenient methods to addYears,addMonths,addWeeks and so on, take a look at the api here.

Java 8

Another possibility is to take advantage of new LocalDate from Java 8 using minusDays(long days) method:

LocalDate dateBefore30Days = LocalDate.now(ZoneId.of("Europe/Paris")).minusDays(30);

Solution 3 - Java

Simply use this to get date before 300 days, replace 300 with your days:

Date date = new Date(); // Or where ever you get it from
Date daysAgo = new DateTime(date).minusDays(300).toDate();

Here,

DateTime is org.joda.time.DateTime;

Date is java.util.Date

Solution 4 - Java

Java 8 Time API:

Instant now = Instant.now(); //current date
Instant before = now.minus(Duration.ofDays(300));
Date dateBefore = Date.from(before);

Solution 5 - Java

As you can see HERE there is a lot of manipulation you can do. Here an example showing what you could do!

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();

//Add one day to current date.
cal.add(Calendar.DATE, 1);
System.out.println(dateFormat.format(cal.getTime()));

//Substract one day to current date.
cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
System.out.println(dateFormat.format(cal.getTime()));

/* Can be Calendar.DATE or
*  Calendar.MONTH, Calendar.YEAR, Calendar.HOUR, Calendar.SECOND
*/

Solution 6 - Java

With Java 8 it's really simple now:

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

A great guide to the new api can be found here.

Solution 7 - Java

In Java 8 you can do this:

Instant inst = Instant.parse("2018-12-30T19:34:50.63Z"); 

// subtract 10 Days to Instant 
Instant value = inst.minus(Period.ofDays(10)); 
// print result 
System.out.println("Instant after subtracting Days: " + value); 

Solution 8 - Java

I have created a function to make the task easier.

  • For 7 days after dateString: dateCalculate(dateString,"yyyy-MM-dd",7);

  • To get 7 days upto dateString: dateCalculate(dateString,"yyyy-MM-dd",-7);


public static String dateCalculate(String dateString, String dateFormat, int days) {
    Calendar cal = Calendar.getInstance();
    SimpleDateFormat s = new SimpleDateFormat(dateFormat);
    try {
        cal.setTime(s.parse(dateString));
    } catch (ParseException e) {
        e.printStackTrace();
    }
    cal.add(Calendar.DATE, days);
    return s.format(cal.getTime());
}

Solution 9 - Java

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;

    }

Solution 10 - Java

You may also be able to use the Duration class. E.g.

Date currentDate = new Date();
Date oneDayFromCurrentDate = new Date(currentDate.getTime() - Duration.ofDays(1).toMillis());

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionyetAnotherSEView Question on Stackoverflow
Solution 1 - JavajmjView Answer on Stackoverflow
Solution 2 - JavaalbciffView Answer on Stackoverflow
Solution 3 - JavaTimView Answer on Stackoverflow
Solution 4 - JavaGrigory KislinView Answer on Stackoverflow
Solution 5 - Javawaldyr.arView Answer on Stackoverflow
Solution 6 - JavaJacob van LingenView Answer on Stackoverflow
Solution 7 - JavaKumar ShanooView Answer on Stackoverflow
Solution 8 - JavareflexgravityView Answer on Stackoverflow
Solution 9 - JavaUcdemirView Answer on Stackoverflow
Solution 10 - JavafbaileyView Answer on Stackoverflow