Android Calendar is not giving expected results

2019-09-20 08:57发布

问题:

I am passing values to calendar instance, but don't know why it is not performing as expected. I want to add one day to a specific date and then use that date.

Log.v("data going to calendar==",
  "year="+Integer.parseInt(fy)+
  "month="+Integer.parseInt(fm)-1)+
  "day="+Integer.parseInt(fd)+
  "hh="+Integer.parseInt(fh)+
  "mm="+Integer.parseInt(fmn));

c.set(
  Integer.parseInt(fd),
  Integer.parseInt(fm)-1,
  Integer.parseInt(fy),
  Integer.parseInt(fh),
  Integer.parseInt(fmn));

c.add(Calendar.DAY_OF_MONTH,1);

Log.v("data coming from calendar==", 
   "year = " + c.get(Calendar.YEAR)+
   "month ="+ c.get(Calendar.MONTH)+
   "day ="+c.get(Calendar.DATE)+
   "hh="+c.get(Calendar.HOUR)+
   "mm="+c.get(Calendar.MINUTE));

output is: data gng to calendar==year = 2013month =7day =29hh=12mm=0

data cmng from calendar==year = 35month =1day =4hh=0mm=0

i run that code by putting comment on code to add one day, but the results are still same except for day, it means adding one day is working perfectly ---> year = 35month =1day =3hh=0mm=0

回答1:

You call the set() method with the wrong parameters. According to the documentation the order must be year, month, date as first three parameters and you call it with date, month, year as the first parameters.

If you change your code to

c.set(Integer.parseInt(fy),
    Integer.parseInt(fm)-1,
    Integer.parseInt(fd),
    Integer.parseInt(fh),
    Integer.parseInt(fmn));

it should work as intended.

The strange values are because it treats 2013 as the day which is approx. 6 years that are added to the date.



回答2:

If you want to add a day - 24 hours - to a date, add it as milliseconds: 1 day = 24 * 60 * 60 * 1000 milliseconds.

Calendar c = Calendar.getInstance();
//Set calendar's fields here
long time = c.getTimeInMilliseconds();
long nextDay = time + 24 * 60 * 60 * 1000;
c.setTimeInMillis(nextDay);