How to get the time difference in Android.
1 min readAug 16, 2020
e.g The time a person is awake by getting the difference between the time they wake up and the time they go to sleep
private fun getNumOfHoursAwake(
startTime: String,
endTime: String
): Int {
/**
* startTime - e.g 21:00
* endTime - e.g 04:00
* expected to return 17
*/
val simpleDateFormat = SimpleDateFormat("HH:mm")
val dateMax: Date = simpleDateFormat.parse(startTime)
val dateMin: Date = simpleDateFormat.parse(endTime)
val startDate = simpleDateFormat.parse(startTime)
val endDate = simpleDateFormat.parse(endTime)
var difference = dateMax.time - dateMin.time
if (difference < 0) {
difference = (dateMax.time - startDate.time) + (endDate.time - dateMin.time)
}
val days = (difference / (1000 * 60 * 60 * 24)).toInt()
val hours = ((difference - 1000 * 60 * 60 * 24 * days) / (1000 * 60 * 60))
return hours.toInt()
}
Happy coding!