218

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?

lukas84
  • 428
  • 3
  • 16
yetAnotherSE
  • 3,178
  • 6
  • 26
  • 33
  • 4
    Obligatory "Use Joda Time" remark. – Steve McLeod Aug 09 '12 at 12:02
  • 1
    The following links might be useful for you.[enter link description here][1] [enter link description here][2] [1]: http://stackoverflow.com/questions/212321/anyone-know-a-simple-way-using-java-calendar-to-subtract-x-days-to-a-date [2]: http://stackoverflow.com/questions/2623610/subtracting-days-in-a-calendar-object – Ami Aug 09 '12 at 12:06
  • FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html) are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [java.time](https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) classes. – Basil Bourque Mar 23 '17 at 21:58

10 Answers10

390

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();
jmj
  • 237,923
  • 42
  • 401
  • 438
  • 22
    It is to set your custom dateInstance in case you don't want to consider current date time – jmj Aug 09 '12 at 12:16
  • 18
    Java's Date handling is *so* bloated! – digory doo Feb 10 '17 at 08: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 – jmj Feb 13 '17 at 11:45
  • FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html), and `java.text.SimpleTextFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [java.time](https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) classes. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Aug 21 '17 at 00: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 May 28 '18 at 14:31
  • Most of the *java.time* functionality is back-ported to Java 6 & Java 7 in the [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/) project. Further adapted for earlier Android in the [***ThreeTenABP***](https://github.com/JakeWharton/ThreeTenABP) project. See [*How to use ThreeTenABP…*](http://stackoverflow.com/q/38922754/642706). – Basil Bourque Dec 04 '18 at 05:24
  • kind of the wrong answer because you're assuming *now* instead of an arbitrary date object – bharal Nov 11 '19 at 23:11
  • @bharal ofcourse you can have instance of LocalDateTime instead. – jmj Nov 11 '19 at 23:14
  • @JigarJoshi i suppose what i'm saying is you need to start with some arbitrary date object, convert it to the localDate, minus, and unconvert, to fully answer the question – bharal Nov 11 '19 at 23:15
70

@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);
albciff
  • 18,112
  • 4
  • 64
  • 89
  • 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](https://stackoverflow.com/a/37658868/642706) by Jacob van Lingen. – Basil Bourque Oct 02 '17 at 05:28
  • 1
    @BasilBourque After your advise, I check the api and you're totally right, therefore I update the answer. thanks. – albciff Oct 02 '17 at 12:41
  • [Brian Montellano](https://stackoverflow.com/users/10106761/brian-montellano) would like to comment: there shouldn’t be any `s` in `DateUtils`, it’s just `DateUtil`. – Ole V.V. Dec 03 '18 at 20:24
  • @OleV.V. Brian Montellano is wrong, you can check the [`DateUtils`](https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/time/DateUtils.html) docs – albciff Nov 12 '19 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

Kishan Solanki
  • 13,761
  • 4
  • 85
  • 82
Tim
  • 463
  • 4
  • 2
  • 9
    The [Joda-Time](http://www.joda.org/joda-time/) project is now in [maintenance mode](https://en.wikipedia.org/wiki/Maintenance_mode), and advises migration to the [java.time](http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) classes. – Basil Bourque Mar 23 '17 at 21:57
34

Java 8 Time API:

Instant now = Instant.now(); //current date
Instant before = now.minus(Duration.ofDays(300));
Date dateBefore = Date.from(before);
Grigory Kislin
  • 16,647
  • 10
  • 125
  • 197
  • 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](http://stackoverflow.com/a/37658868/642706). – Basil Bourque Nov 26 '16 at 20:58
  • Java 8 of cause, fixed – Grigory Kislin Nov 27 '16 at 12:40
  • so close, but should be for modifying an arbitrary date object, not "now" – bharal Nov 11 '19 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
*/
waldyr.ar
  • 14,424
  • 6
  • 33
  • 64
  • @Jigar Joshi: I didn't see your answer... Should I delete mine? – waldyr.ar Aug 09 '12 at 12:12
  • FYI, the terribly troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Dec 04 '18 at 05:25
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.

Jacob van Lingen
  • 8,989
  • 7
  • 48
  • 78
  • 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" )`. – Basil Bourque Jun 06 '16 at 19:56
  • needs to be on an arbitrary date object as per the question, not "now" – bharal Nov 11 '19 at 23:12
3

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); 
Benjamin Zach
  • 1,452
  • 2
  • 18
  • 38
Kumar Shanoo
  • 125
  • 4
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());
}
Kalamarico
  • 5,466
  • 22
  • 53
  • 70
reflexgravity
  • 910
  • 10
  • 17
  • This Answer uses troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` that are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [java.time](https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) classes. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Oct 01 '17 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. – Basil Bourque Oct 01 '17 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());
fbailey
  • 303
  • 5
  • 17
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;

    }
Ucdemir
  • 2,852
  • 2
  • 26
  • 44