1

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.

Ritesh Kumar Gupta
  • 5,055
  • 7
  • 45
  • 71
Jayesh_naik
  • 375
  • 3
  • 7
  • 17

2 Answers2

5

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

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • `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` – Jayesh_naik Apr 16 '13 at 14:04
  • I added output to my test, it's 15 Apr 2013 – Evgeniy Dorofeev Apr 16 '13 at 14:04
  • Ah, got you, 3 is Apr, months start from 0 in Calendar – Evgeniy Dorofeev Apr 16 '13 at 14:07
2

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

0-> January
1-> February
2-> March
3-> April.

What you mean:

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

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

Pablo Lozano
  • 10,122
  • 2
  • 38
  • 59