Calculate Difference between two times in Android

后端 未结 7 2123
-上瘾入骨i
-上瘾入骨i 2020-11-27 21:47

I have two string variables such as StartTime and EndTime. I need to Calculate the TotalTime by subtracting the EndTime with StartTime.

The Format of StartTime and E

7条回答
  •  心在旅途
    2020-11-27 22:31

    Try below code.

    // suppose time format is into ("hh:mm a") format

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm a");
    
    date1 = simpleDateFormat.parse("08:00 AM");
    date2 = simpleDateFormat.parse("04:00 PM");
    
    long difference = date2.getTime() - date1.getTime(); 
    days = (int) (difference / (1000*60*60*24));  
    hours = (int) ((difference - (1000*60*60*24*days)) / (1000*60*60)); 
    min = (int) (difference - (1000*60*60*24*days) - (1000*60*60*hours)) / (1000*60);
    hours = (hours < 0 ? -hours : hours);
    Log.i("======= Hours"," :: "+hours);
    

    Output - Hours :: 8

提交回复
热议问题