How to compare date Time to date in kotlin Android
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💖💖