Friday 29 March 2024

Find Hours Diffrence in Kotlin

 In Kotlin, determining the difference in hours between two timestamps is a common task, especially in scenarios involving time-based calculations. By leveraging Kotlin's interoperability with Java's date and time API, achieving this functionality becomes straightforward.

Below is a concise function to compute the hour difference between two timestamps:

This code is find the hours diffrence from current date to given date.

@RequiresApi(Build.VERSION_CODES.O)
fun calculateHoursDifference(dateString: String): Long {
 val currentDate = LocalDateTime.now()

val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
val givenDate = LocalDateTime.parse(dateString, formatter)

return ChronoUnit.HOURS.between(givenDate, currentDate)
}

// This is the where i want to find the hours difference in Activity or Fragment
val dateString = "2024-03-30 05:00:04"
val hoursDifference =
Utils.calculateHoursDifference(dateString)

println("Hours difference: $hoursDifference")


No comments:

Post a Comment

Comments

Find Hours Diffrence in Kotlin

  In Kotlin, determining the difference in hours between two timestamps is a common task, especially in scenarios involving time-based calcu...