Calculate Difference between two times in Android

后端 未结 7 2114
-上瘾入骨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条回答
  •  Happy的楠姐
    2020-11-27 22:16

    Note: Corrected code as below which provide by Chirag Raval because in code which Chirag provided had some issues when we try to find time from 22:00 to 07:00.

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
    Date startDate = simpleDateFormat.parse("22:00");
    Date endDate = simpleDateFormat.parse("07:00");
    
    long difference = endDate.getTime() - startDate.getTime(); 
    if(difference<0)
    {
        Date dateMax = simpleDateFormat.parse("24:00");
        Date dateMin = simpleDateFormat.parse("00:00");
        difference=(dateMax.getTime() -startDate.getTime() )+(endDate.getTime()-dateMin.getTime());
    }
    int days = (int) (difference / (1000*60*60*24));  
    int hours = (int) ((difference - (1000*60*60*24*days)) / (1000*60*60)); 
    int min = (int) (difference - (1000*60*60*24*days) - (1000*60*60*hours)) / (1000*60);
    Log.i("log_tag","Hours: "+hours+", Mins: "+min); 
    

    Result will be: Hours: 9, Mins: 0

提交回复
热议问题