Title: Date difference from current date in java
Tags: java
Question: I am developing an application in JAVA swing, in that I wanted the date difference from current date like if today is ```16/04/2013``` then it should return ```15/04/2013```. I have tried the following code:

```Calendar cal = new GregorianCalendar();
Calendar cal2 = new GregorianCalendar();
cal.roll(Calendar.DAY_OF_YEAR, -1);
//if within the first 30 days, need to roll the year as well
if(cal.after(cal2)){
     cal.roll(Calendar.YEAR, -1);
}
System.out.println("Year " + cal.get(Calendar.YEAR));
System.out.println("Month " + cal.get(Calendar.MONTH));
System.out.println("Day " + cal.get(Calendar.DAY_OF_MONTH));
```

In this code I was expecting to get one day back date. But instead I am getting  one month back date.
Ex. if today is ```16/04/2013```, the expected output is ```15/04/2013```, but I am getting  15/03/2013 ( one month one day back) as an output.

Comment: Are you obliged to use Calendar or would it be acceptable to use JodaTime?

Comment: This has been answered before: http://stackoverflow.com/questions/3299972/difference-in-days-between-two-dates-in-java

Comment: Joda library stuns, I suggest it.

Comment: try `cal.add(Calendar.DAY_OF_MONTH, -1);`


Here is another answer: That's a classic example why java.util.Date implementation sucks: Months numeration starts in zero:

```0-&gt; January
1-&gt; February
2-&gt; March
3-&gt; April.
```

What you mean:

```new Date(10,1,2013) //10th of January of 2013
```

What you get: 10th of February of 3983 (1970+2013)


Here is another answer: You dont need any manual manipulations, Calendar will do all necessary date arithmetic automatically, simply do this

```    Calendar cal = new GregorianCalendar();
    cal.add(Calendar.DATE, -1);
```

Note that months in Calendar start from 0 so April is 3

Comment for this answer: I added output to my test, it's 15 Apr 2013
Comment for this answer: Ah, got you, 3 is Apr, months start from 0 in Calendar
Comment for this answer: `Calendar cal = new GregorianCalendar();
        cal.add(Calendar.DATE, -1);
        System.out.println("Year " + cal.get(Calendar.YEAR));
        System.out.println("Month " + cal.get(Calendar.MONTH));
        System.out.println("Day " + cal.get(Calendar.DAY_OF_MONTH));`                       this is what output im getting
        `Year 2013
        Month 3
        Day 15`

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 2, 'CommentCount': 4, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2013:00:04/16/13', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<java>', 'Title': 'Date difference from current date in java', 'ViewCount': 458, 'id': 16038763, 'user_AboutMe': '', 'user_AccountId': 2259226.0, 'user_DisplayName': 'Jayesh_naik', 'user_Reputation': 365.0, 'user_Views': 49.0, 'user_id': 1989696.0}}