Kotlin: 根据字符串日期减一天
学习笔记作者:admin日期:2025-05-29点击:21
摘要:通过 Kotlin 和 Java 8 的 LocalDate 类,实现从字符串日期 "2025-01-01" 减一天得到 "2024-12-31",兼容 API Level 24 及以上。
Kotlin: 根据字符串日期减一天
问题描述
需要根据字符串日期 "2025-01-01" 减去一天,得到结果字符串 "2024-12-31",同时确保兼容 Android API Level 24 及以上。
解决方案
使用 Kotlin 和 java.time
包中的 LocalDate
类完成日期解析、减法运算和格式化。
代码实现
import java.time.LocalDate
import java.time.format.DateTimeFormatter
fun main() {
// 原始日期字符串
val dateString = "2025-01-01"
// 定义日期格式
val formatter = DateTimeFormatter.ISO_LOCAL_DATE
// 将字符串解析为 LocalDate 对象
val date = LocalDate.parse(dateString, formatter)
// 减去一天
val previousDate = date.minusDays(1)
// 将结果格式化为字符串
val result = previousDate.format(formatter)
// 输出结果
println(result) // 输出: 2024-12-31
}
兼容性说明
java.time
包从 Android API Level 26 开始引入,但 API Level 24 和 25 也可通过 ThreeTenABP 库实现兼容。
总结
通过 LocalDate
和 DateTimeFormatter
,可以轻松实现日期减法运算并返回字符串结果,确保兼容 API Level 24 及以上。