1

I am trying to write code to find the Day difference between tow date but Calendar.getInstance() keep getting the date for previous month instead of current month for example :Current 17/7/2014 it get 17/6/2014 my code :

 TextView textview=(TextView) findViewById (R.id.textView1);

  Calendar cal = Calendar.getInstance();

 Calendar startDate=Calendar.getInstance();
 startDate.set(Calendar.DAY_OF_MONTH, 1);
 startDate.set(Calendar.MONTH,1);
    startDate.set(Calendar.YEAR, 2013);

long diff=(((cal.getTimeInMillis()-startDate.getTimeInMillis())/(1000*60*60*24))+1);
    String sdiff=String.valueOf(diff);

    String stt=cal.get(Calendar.YEAR) +"_"+cal.get(Calendar.MONTH)+"_"+cal.get(Calendar.DAY_OF_MONTH);
    textview.setText(stt);
  • possible duplicate of [Java Gregorian Calendar Returns Wrong Month](http://stackoverflow.com/questions/20367546/java-gregorian-calendar-returns-wrong-month) – Barett Jul 17 '14 at 20:59

2 Answers2

3

Months start at 0, not at 1, but you really don't have to worry about this if you don't use magic numbers when getting or setting month but instead use the constants. So not this:

startDate.set(Calendar.MONTH,1);  // this is February!

but rather

startDate.set(Calendar.MONTH, Calendar.JANUARY);
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • Thinks but the wrong value com form Calendar cal = Calendar.getInstance() it show the date 17/6/2014 not the current date 17/7/2014 – user3849607 Jul 17 '14 at 21:22
  • Thinks for your information ,now I understand where is the error I fix it using cal.add(Calendar.Month,1); – user3849607 Jul 17 '14 at 21:44
0

Months in Java's Calendar start with 0 for January, so July is 6, not 7.

Calendar.MONTH javadocs:

The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0

Add 1 to the result of get.

(cal.get(Calendar.MONTH) + 1)

This also affects your set call. You can either subtract 1 when passing a month number going in, or you can use a Calendar constant, e.g. Calendar.JANUARY.

You can also use a SimpleDateFormat to convert it to your specific format, without having to worry about this quirk.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd");
String stt = sdf.format(cal.getTime());
rgettman
  • 176,041
  • 30
  • 275
  • 357