How to compare the famous clock of the current hour in Android?

I am trying to use the start hour and the end hour and calculate the percentages of the current time (which is between startHour and endHour). For example, if the time is now 12:00 and startHour = 11:00 and End Hour = 14:00, it should return 33 (rounded), because 33% of the time has passed.

I tried the following, but maybe I'm mixing different formats ... I don't know:

double currentTime = Calendar.getInstance().getTimeInMillis(); double startTime = Time.UTC(2012, 3, 20, 22, 0, 0); double endTime = Time.UTC(2012, 3, 20, 23, 30, 0); int prg = (int)((currentTime - startTime)/(endTime - startTime)); 

in this code, I assume that the current hour is between 22:00 and 23:30

Thanks Eyal

+2
source share
2 answers

I tried myself and found an error, getting the time in milliseconds for the Current Time calendar instance.

You got an error because the time in milisecond for CurrentTime was not accurate , it was somehow an error, but it was 1 month less than the current time , so why did you get the answer in the local.

You can do this below.

  Calendar calCurr = Calendar.getInstance(); Log.i("Time in mili of Current - Normal", ""+calCurr.getTimeInMillis()); // see what it gives? dont know why? Date date = new Date(); calCurr.set(date.getYear()+1900, date.getMonth()+1, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());// so added one month to it Log.i("Time in mili of Current - after update", ""+calCurr.getTimeInMillis()); // now get correct Calendar start = Calendar.getInstance(); start.set(2012, 12, 1, 11, 28, 0); Calendar end = Calendar.getInstance(); end.set(2012, 12, 1, 13, 28, 0); if((start.compareTo(calCurr)==-1) && (calCurr.compareTo(end)==-1) && (start.compareTo(end)==-1)) { double hrBetweenStartEnd = (end.getTimeInMillis()-start.getTimeInMillis())/3600000; double hrBetweenStartCurr = (calCurr.getTimeInMillis()-start.getTimeInMillis())/3600000; int percentage = (int) ((100*hrBetweenStartCurr)/hrBetweenStartEnd); Log.i("Percentage", ""+percentage); } 
0
source

I do not program android, but I am sure that the problem is that the months are based on zero (January = 0), i.e. 3 - not March, but April.

That is, Time.UTC(2012, 3, 20, 22, 0, 0) does not represent 22:00 on March 20, but on April 20. So, the current time was about one month before that time.

0
source

Source: https://habr.com/ru/post/912375/


All Articles