How to compare date Time to date in kotlin Android

Sudish Kumar
1 min readJan 25, 2021

--

When I was trying to compare date time with date . My date time was in the string and on that time in comparing I was getting error then I change date time String to LocalDateTime Format after that I tried to compare then it is working fine.

We will compare today date to given date Time(2021–01–21T17:16)

val calender = Calendar.getInstance()

val year = calender.get(Calendar.YEAR)
val month = calender.get(Calendar.MONTH) + 1
val day = calender.get(Calendar.DAY_OF_MONTH)
val todayDate = "$year-0$month-$day"
val convertedTodayDate = LocalDate.parse(todayDate)

val convertedDate = LocalDateTime.parse("2021-01-21T17:16")
val date = convertedDate.toLocalDate()
val dateFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)
val formattedExpiryDate = date.format(dateFormatter)
val formattedTodayDate = convertedTodayDate.format(dateFormatter)


if (formattedExpiryDate?.compareTo(formattedTodayDate)!! >0){
Toast.makeText(this, "Today date is less than given date", Toast.LENGTH_SHORT).show()

}else if(formattedExpiryDate?.compareTo(formattedTodayDate)!! <0){
Toast.makeText(this, "Today date is gretter than given date", Toast.LENGTH_SHORT).show()

}else if(formattedExpiryDate?.compareTo(formattedTodayDate) ==0){
Toast.makeText(this, "Both date is same or date is matched", Toast.LENGTH_SHORT).show()
}

Thank you for reading this article💖💖

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Sudish Kumar
Sudish Kumar

Written by Sudish Kumar

Flutter | Android | Node | Dart | Kotlin | Java | JavaScript | TypeScript | PHP | Short Story Teller | Tech Lead

No responses yet

Write a response