The problem is as follows:
The application should display the work shift in the schedule for the selected date. To do this, it counts the number of days from a specific date, divides by 12 (the length of the cycle) and displays the remainder of the division.

On one device, the algorithm worked correctly. However, when installing the application to another device, an error appeared on one day.

String d1 = "02.11.1945"; Int year = mDatePicker.getYear(); Int month = mDatePicker.getMonth(); month = month + 1; Int day = mDatePicker.getDayOfMonth(); String d2 = (day +"." + month + "." + year); SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy"); Date date1 = null; Date date2 = null; try { date1 = format.parse(d1); date2 = format.parse(d2); } catch (Exception e) { e.printStackTrace(); } long difference = date2.getTime() - date1.getTime(); long days = difference / (24 * 60 * 60 * 1000); Long result = days%12; 

When I displayed the totals of all the variables in TextViev, it turned out that on different phones the days had a difference of one day.
Accordingly, the problem in calculating the difference .
Why this could be, and how to fix it?
(Date d1 is chosen randomly)

  • and what about date1 and date2 are they correct? - Boris Safonov
  • Are the time zones the same on both devices? - Suvitruf

1 answer 1

date1 and date2 are the same.
But time zones are different. But how can this affect?

Now rummage, and found that glitches start if the time zone is Ekaterinburg . It is listed in the settings as GMT + 6, but in general we have GMT + 5. I fixed the belt on another GMT + 5 and everything worked correctly.

I solved the problem by checking the correctness of the counting. Added the following code

 String dTest = "01.11.2016"; SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy"); Date date1 = null; Date date2 = null; Date TestDate = null; try { date1 = format.parse(d1); date2 = format.parse(d2); TestDate = format.parse(dTest); } catch (Exception e) { e.printStackTrace(); } long difference = date2.getTime() - date1.getTime(); long days = difference / (24 * 60 * 60 * 1000); long diffTest = TestDate.getTime() - date1.getTime(); long daysT = diffTest / (24 * 60 * 60 * 1000); Long resultT = daysT%12; //при правильном расчете получаем ноль days = days - resultT; //если нет, то количество дней уменьшается на погрешность Long result = days%12; //и остаток от деления все равно получаем правильный. 

Vobschem added checking the calculation of the number of days. When properly validated between two dates, the remainder of the division is zero. If the calculations are not correct, then we subtract the test balance from the obtained number of days. In the end, all the same we have the correct remainder of the division.
Thanks to all! The question is closed!