实现思路
- 使用 Kotlin 标准库中的
LocalDate
类来获取当前日期。LocalDate
类提供了处理日期的功能。
- 使用
DateTimeFormatter
类来定义日期格式化模式。这里需要的模式是 yyyy - MM - dd
。
- 调用
LocalDate
对象的 format
方法,传入定义好的 DateTimeFormatter
对象,将 LocalDate
格式化为指定格式的字符串。
代码示例
import java.time.LocalDate
import java.time.format.DateTimeFormatter
fun main() {
// 获取当前日期
val currentDate = LocalDate.now()
// 定义日期格式化模式
val formatter = DateTimeFormatter.ofPattern("yyyy - MM - dd")
// 将当前日期格式化为指定字符串形式
val formattedDate = currentDate.format(formatter)
println(formattedDate)
}