Skip to content

Instantly share code, notes, and snippets.

@AkshayChordiya
Last active May 26, 2023 13:39
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save AkshayChordiya/b1c9788d24e62d92e3e20778288e64a8 to your computer and use it in GitHub Desktop.
Save AkshayChordiya/b1c9788d24e62d92e3e20778288e64a8 to your computer and use it in GitHub Desktop.
Use these date related top-level Kotlin functions to show sections like "Today", "Yesterday" and so on

Date header top-level Kotlin functions

There are several apps which show a list with sections like "Today", "Yesterday" and so on like Inbox Android app

I wrote few top-level functions which are helpful to check if the date is upcoming, tomorrow, today, yesterday, this month, this week or older to show sections in my app

PS: I used SectionedRecyclerView library to show sections in my app.

Dependency:

import org.joda.time.LocalDate
/**
* @return true if the supplied date is in the future else false
*/
fun isUpcoming(millis: Long): Boolean {
return !isTomorrow(millis) && LocalDate(millis).isAfter(LocalDate.now())
}
/**
* @return true if the supplied date is tomorrow else false
*/
fun isTomorrow(millis: Long): Boolean {
return LocalDate.now().plusDays(1).compareTo(LocalDate(millis)) == 0
}
/**
* @return true if the supplied date is today else false
*/
fun isToday(millis: Long): Boolean {
return LocalDate.now().compareTo(LocalDate(millis)) == 0
}
/**
* @return true if the supplied when is yesterday else false
*/
fun isYesterday(millis: Long): Boolean {
return LocalDate.now().minusDays(1).compareTo(LocalDate(millis)) == 0
}
/**
* @return true if the supplied when is this week else false
*/
fun isThisWeek(millis: Long): Boolean {
return LocalDate.now().minusWeeks(1) <= LocalDate(millis)
}
/**
* @return true if the supplied when is this month else false
*/
fun isThisMonth(millis: Long): Boolean {
return LocalDate.now().minusMonths(1) <= LocalDate(millis)
}
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class TimeHelperTest {
@Test
fun isTodayTest() {
// 21/01/2018 : 14:22
assertEquals(true, isToday(1516524740355))
}
@Test
fun isYesterdayTest() {
// 20/01/2018 : 20:00
assertEquals(true, isYesterday(1516458600000))
}
@Test
fun isThisWeekTest() {
// 18/01/2018 : 20:00
assertEquals(true, isThisWeek(1516285800000))
}
@Test
fun isThisMonthTest() {
// 11/01/2018 : 20:00
assertEquals(true, isThisMonth(1515681000000))
}
}
// Example usage
when {
isUpcoming(time) -> {}
isTomorrow(time) -> {}
isToday(time) -> {}
isYesterday(time) -> {}
isThisWeek(time) -> {}
isThisMonth(time) -> {}
else -> {
// Else branch means the date is older
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment