How to get number of days between two calendar instance?

后端 未结 11 1090
孤城傲影
孤城傲影 2020-12-05 01:58

I want to find the difference between two Calendar objects in number of days if there is date change like If clock ticked from 23:59-0:00 there should be a day

11条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-05 02:32

    Kotlin solution, purely relies on Calendar. At the end gives exact number of days difference. Inspired by @Jk1

     private fun daysBetween(startDate: Calendar, endDate: Calendar): Long {
            val start = Calendar.getInstance().apply {
                timeInMillis = 0
                set(Calendar.DAY_OF_YEAR, startDate.get(Calendar.DAY_OF_YEAR))
                set(Calendar.YEAR, startDate.get(Calendar.YEAR))
            }.timeInMillis
            val end = Calendar.getInstance().apply {
                timeInMillis = 0
                set(Calendar.DAY_OF_YEAR, endDate.get(Calendar.DAY_OF_YEAR))
                set(Calendar.YEAR, endDate.get(Calendar.YEAR))
            }.timeInMillis
            val differenceMillis = end - start
            return TimeUnit.MILLISECONDS.toDays(differenceMillis)
        }
    

提交回复
热议问题