-3

I am developing alarm application where multiple alarm will fire on their selected time. Now problem is that I want to calculate the time difference between current time and the alarm time (which user has selected). How can I calculate the time difference between the current time and the alarm time selected by user without using threads. Is there any time difference method which directly calculates the time?

Momin Khan
  • 147
  • 10
  • Convert the 2 times into `long` and make some subtraction. – Enzokie Nov 01 '16 at 06:52
  • thats the obvious one #enzokie but i just found what i was searching.. thanks anyway... here is easy way to do this. http://stackoverflow.com/questions/3352031/calculate-time-between-two-times-android – Momin Khan Nov 01 '16 at 06:56
  • That's just the same approach that I am saying a while ago. – Enzokie Nov 01 '16 at 07:07
  • Possible duplicate of [Calculate difference between two times android](https://stackoverflow.com/questions/18908738/calculate-difference-between-two-times-android) – Basil Bourque Jul 16 '17 at 05:54

2 Answers2

0

This will give you the difference between two times.

try {
    Date _day = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss", Locale.ENGLISH).parse(nowTime);
    Date day = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss", Locale.ENGLISH).parse(alarmTime);

    double diff = day.getTime() - _day.getTime() ;

    double totalMinuts = diff / (60 * 1000);
    double leftMinutsAfterHours = totalMinuts % 60;
    double totalHours = (totalMinuts - leftMinutsAfterHours) / 60;

    double leftHoursAfterDays = totalHours % 24;
    double totalDays = (totalHours - leftHoursAfterDays) / 24;

} catch (ParseException e) {
    e.printStackTrace();
}
vidulaJ
  • 1,232
  • 1
  • 16
  • 31
0

Convert time to Calander object

If you are using TimePickerDialog then.

Calander c=Calander.getinstance();

set hours and minuits

then take the millis.

then take the diffenece;

long differnce=pickedTimeInMillis- currentTimeInMillis;

long diffenceInSeconds=diffenrce/1000;
int differnceInMin=deffernce/(1000*60)
int differnceInHour=deffernce/(1000*60*60)

Or you can do without taking millis

Calander currentTime=Calander.getinstance();
hour=c.get(Calendar.HOUR_OF_DAY)
Calander selectedTime=selectedTimeFromCalander;

int differnce=selectedTime.get(Calendar.HOUR_OF_DAY)-hour
noobEinstien
  • 3,147
  • 4
  • 24
  • 42
  • Please check . i didnt test it , just wrote only. Take absolute value and the hour is in 12 hour format so you want to check it with Am or Pm – noobEinstien Nov 01 '16 at 08:03