222

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?

3

10 Answers 10

397

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();
9
  • 22
    It is to set your custom dateInstance in case you don't want to consider current date time Commented Aug 9, 2012 at 12:16
  • 20
    Java's Date handling is so bloated!
    – digory doo
    Commented Feb 10, 2017 at 8:09
  • 1
    This is 4 year old answer. there have been new DateTime API changes made to recent versions of it. I will edit the answer Commented Feb 13, 2017 at 11:45
  • FYI, the troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleTextFormat are now legacy, supplanted by the java.time classes. See Tutorial by Oracle. Commented Aug 21, 2017 at 0:50
  • @JigarJoshi it would be terrific if you updated your answer with the Java 8 API. Your answer is the accepted one that people see first.
    – jotaen
    Commented May 28, 2018 at 14:31
74

@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);
4
  • No point to using LocalDateTime as that class purposely has no concept of time zone nor offset-from-UTC. Use that only when zone/offset is unknown or not relevant. Instead use LocalDate and pass a ZoneId when calling its now method. See the correct Answer by Jacob van Lingen. Commented Oct 2, 2017 at 5:28
  • 1
    @BasilBourque After your advise, I check the api and you're totally right, therefore I update the answer. thanks.
    – albciff
    Commented Oct 2, 2017 at 12:41
  • Brian Montellano would like to comment: there shouldn’t be any s in DateUtils, it’s just DateUtil.
    – Anonymous
    Commented Dec 3, 2018 at 20:24
  • @OleV.V. Brian Montellano is wrong, you can check the DateUtils docs
    – albciff
    Commented Nov 12, 2019 at 13:30
43

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

1
37

Java 8 Time API:

Instant now = Instant.now(); //current date
Instant before = now.minus(Duration.ofDays(300));
Date dateBefore = Date.from(before);
3
  • I must mean Java 8 API, not 7. And mentioning the package java.time might help. Also, some discussion/explanation is generally expected on Stack Overflow rather than just a code snippet. You should definitely explain Duration as that is the added-value of your Answer over the existing one by van Lingen. Commented Nov 26, 2016 at 20:58
  • Java 8 of cause, fixed Commented Nov 27, 2016 at 12:40
  • so close, but should be for modifying an arbitrary date object, not "now"
    – bharal
    Commented Nov 11, 2019 at 23:13
12

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
*/
2
10

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.

2
  • 4
    I suggest always passing the optional time zone (or offset-from-UTC) to that now method. If omitted, the JVM‘s current default time zone is implicitly and silently applied. That default lies outside your control and can change at any moment, even during runtime. Example: LocalDate.now( ZoneId.of( "America/Montreal" ). Commented Jun 6, 2016 at 19:56
  • needs to be on an arbitrary date object as per the question, not "now"
    – bharal
    Commented Nov 11, 2019 at 23:12
4

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); 
1

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());
}
2
  • This Answer uses troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat that are now legacy, supplanted by the java.time classes. See Tutorial by Oracle. Commented Oct 1, 2017 at 22:12
  • The Question involves date-time objects, not generating strings. By the way, LocalDate.parse( "2017-01-23").plusWeeks( 1 ) is simpler than writing your own method and is more self-documenting. Commented Oct 1, 2017 at 22:14
1

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());
0

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;

    }

Not the answer you're looking for? Browse other questions tagged or ask your own question.