0

I had try to get day different between two specific date using below code but the same date passed in return a different value for android below and above android 6.0

here is my function to get the day count:

Calendar cal = Calendar.getInstance();
Calendar base_cal = Calendar.getInstance();
baseDate = chineseDateFormat.parse("1900-1-3");
        base_cal.setTime(baseDate);
int offset = (int) ((cal.getTimeInMillis() - base_cal.getTimeInMillis()) / 86400000L);

I realized that the cal.getTimeInMillis() can return the same value for different os version but base_cal.getTimeInMillis() will return different value for different android os version and it always different by one day

MinFu
  • 353
  • 1
  • 13
  • If you cannot find a reasonable answer, try working with "unix epoch". I've used this and works. Additionally, if you're not aware about that, 2016 is a leap year - maybe this is acting on the results you're getting. Best. – statosdotcom Jul 07 '16 at 02:49
  • Are you sure your "chineseDateFormat" object is defined correctly? – Ken Cheung Jul 07 '16 at 02:58
  • yes the chineseDateFormat object is defined correctly – MinFu Jul 07 '16 at 03:12

1 Answers1

2

Your "baseDate" is the result of parsing a date string. I don't read Chinese, so I can't tell what the format is, but I suspect that the problem is that your parsed date has a different time of day from the date returned by getTimeInMillis(), and the result is a rounding error.

I further suspect that what you expect is the difference between the two dates, without respect to time of day.

The easiest way to do this correctly and repeatably is to use the Joda date library. There's a port specifically for Android at https://github.com/dlew/joda-time-android

You can see an example at Number of days between two dates in Joda-Time

Community
  • 1
  • 1
GreyBeardedGeek
  • 29,460
  • 2
  • 47
  • 67
  • 1
    Actually, Joda-Time has been supplanted by the java.time framework built into Java 8 and later. Much of the java.time functionality is back-ported to Java 6 & 7 in the [ThreeTen-Backport](http://www.threeten.org/threetenbp/) project, and further adapted to Android in [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP). – Basil Bourque Jul 07 '16 at 07:11