Find total hours between two Dates

前端 未结 11 1363
抹茶落季
抹茶落季 2020-11-28 06:00

I have two Date objects and I need to get the time difference so I can determine the total hours between them. They happen to be from the same day. The result I would like w

11条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 06:52

    for kotlin, you can use below function and get hours between two date

    private val dateFormat: String = "yyyy-MM-dd @ hh:mm a"
    val startDate = SimpleDateFormat(dateFormat).parse("2018-10-01 @ 12:33 PM")
    val endDate = SimpleDateFormat(dateFormat).parse("2018-10-01 @ 02:46 PM")
    
    private fun hoursDifference(date1: Date, date2: Date): Int {
        val milliToHour : Long = 1000 * 60 * 60
        return ((date1.time - date2.time) / milliToHour).toInt()
    }
    
    println(hoursDifference(endDate,startDate).toString())
    

    Output: 2

提交回复
热议问题