Skip to content

Instantly share code, notes, and snippets.

@hrules6872
Forked from bagus2x/Calendar.kt
Last active April 4, 2023 18:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hrules6872/634e5039a9255c20e2cacbccc65881fc to your computer and use it in GitHub Desktop.
Save hrules6872/634e5039a9255c20e2cacbccc65881fc to your computer and use it in GitHub Desktop.
Jetpack Compose Simple calendar
@Composable
private fun Calendar(
modifier: Modifier = Modifier,
date: LocalDate
) {
val firstDate = with(date) {
val firstOfMonth = withDayOfMonth(1)
val firstDayOfFirstWeek = firstOfMonth.dayOfWeek.value
firstOfMonth.minusDays(firstDayOfFirstWeek.toLong())
}
val daysOfWeek = DateFormatSymbols().shortWeekdays.drop(1).run {
if (!isSundayFirstDayOfWeek()) this.rotateLeft(1) else this
}
Column(modifier = modifier.fillMaxWidth()) {
Row(modifier = Modifier
.fillMaxWidth()
.padding(bottom = AppTheme.dimens.paddingSmall)) {
daysOfWeek.forEach { dayOfWeek ->
Text(
text = dayOfWeek,
modifier = Modifier.weight(1f),
textAlign = TextAlign.Center,
maxLines = 1,
style = AppTheme.typography.caption
)
}
}
LazyVerticalGrid(columns = GridCells.Fixed(count = DAYS_IN_A_WEEK)) {
items(DAYS_IN_A_WEEK * 6) { index -> // 6 rows
val day = firstDate.plusDays(index.toLong()).run {
if (!isSundayFirstDayOfWeek()) this.plusDays(1) else this
}
val isInCurrentMonth = day.month == date.month
Text(
text = day.dayOfMonth.toString(),
textAlign = TextAlign.Center,
color = when {
day.isToday() -> AppTheme.colors.primary
isInCurrentMonth -> Color.Unspecified
else -> AppTheme.colors.outline
},
fontWeight = if (day.isToday()) FontWeight.Bold else null,
style = AppTheme.typography.caption
)
}
}
}
}
private const val DAYS_IN_A_WEEK = 7
private fun isSundayFirstDayOfWeek(): Boolean = WeekFields.of(Locale.getDefault()).firstDayOfWeek.isSunday()
private fun DayOfWeek.isSunday(): Boolean = this == DayOfWeek.SUNDAY
private fun <TYPE> List<TYPE>.rotateLeft(n: Int): List<TYPE> = when {
n.isGreaterThanZero() && n < this.size -> drop(n) + take(n)
else -> this
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment