I'm currently trying to determine the amount of time between two dates (one of which is the present date/time, the other an arbitrary future date). I'm using native Java and the Android API only, but I'm having a few problems with GregorianCalendar. My code so far can be seen below, but the problem I'm having is that the time between the two dates is massively inaccurate. As you'll be able to see I've set the future date as Christmas day in this example, but it's telling me there's over 62 days until then, which is clearly wrong.
date = new GregorianCalendar();
currentTime = date.getTimeInMillis();
calendar = new GregorianCalendar();
calendar.set(2011, 12, 25, 0, 0, 0);
long difference = calendar.getTimeInMillis()-currentTime;
long x = difference / 1000;
seconds = x % 60;
x /= 60;
minutes = x % 60;
x /= 60;
hours = x % 24;
x /= 24;
days = x;
While debugging I added date.set(2011, 11, 23, 13, 1, 15); which was much more accurate, but it still displayed 32 days when I believe the correct amount of days is 31.
Thanks very much in advance for any help, much appreciated.
解决方案
the problem in your code is the method calendar.set(2011, 12, 25, 0, 0, 0);
what you want is calendar.set(2011, 11, 25, 0, 0, 0);
you can use Calendar.DECEMBER too.
The javadoc is clear for this method:
@param month the value used to set the MONTH calendar
field. * Month value is 0-based. e.g., 0 for January.