不要使用旧的Calendar 和SimpleDateForamt api,它是outdated and troublesome
使用LocalDateTime获取系统日期和时间。
当前日期
val dateTime = LocalDateTime.now() // current date
val formatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM) // date time formatter
Log.d("Date:", "parssed date ${dateTime.format(formatter)}")
上一个日期
button.setOnClickListener {
val previousDate = dateTime.minusDays(1)
Log.d("Date:", "previous date ${previousDate.format(formatter)}")
}
下一个日期
button.setOnClickListener {
val nextDate = dateTime.plusDays(1)
Log.d("Date:", "next date ${nextDate.format(formatter)}")
}
输出:
当前日期 - 2021 年 12 月 9 日
上一个日期 - 2021 年 12 月 8 日
下一个日期 - 2021 年 12 月 10 日
注意:LocalDateTime仅适用于android 8及以上,在android 8以下使用enable desugaring