简体   繁体   中英

Android , Calendar.getInstance() not giving the correct month

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

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

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, eg 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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM