MST

星途 面试题库

面试题:Kotlin日期时间处理库之基础操作

在Kotlin中,使用日期时间处理库获取当前日期,将其格式化为'yyyy - MM - dd'的字符串形式,并说明如何将这个字符串再转换回日期对象。
21.8万 热度难度
编程语言Kotlin

知识考点

AI 面试

面试题答案

一键面试
  1. 获取当前日期并格式化为'yyyy - MM - dd'的字符串形式
    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)
    }
    
  2. 将这个字符串再转换回日期对象
    import java.time.LocalDate
    import java.time.format.DateTimeFormatter
    
    fun main() {
        val dateString = "2023 - 10 - 05"
        val formatter = DateTimeFormatter.ofPattern("yyyy - MM - dd")
        val date = LocalDate.parse(dateString, formatter)
        println(date)
    }
    

在上述代码中,java.time.LocalDate是Java 8引入的日期时间API,在Kotlin中可以直接使用。DateTimeFormatter用于定义日期时间的格式化模式。LocalDate.now()获取当前日期,currentDate.format(formatter)将当前日期格式化为指定的字符串形式。LocalDate.parse(dateString, formatter)则是将指定格式的字符串解析为LocalDate对象。