MST

星途 面试题库

面试题:Kotlin 中如何获取当前日期并格式化成年 - 月 - 日的形式

在 Kotlin 中,利用相关日期与时间处理的类和方法,实现获取当前日期,并将其格式化为 'yyyy - MM - dd' 的字符串形式,简述实现思路并给出代码示例。
15.6万 热度难度
编程语言Kotlin

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 使用 Kotlin 标准库中的 LocalDate 类来获取当前日期。LocalDate 类提供了处理日期的功能。
  2. 使用 DateTimeFormatter 类来定义日期格式化模式。这里需要的模式是 yyyy - MM - dd
  3. 调用 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)
}