面试题答案
一键面试- 获取当前日期并格式化为
'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) }
- 将这个字符串再转换回日期对象:
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
对象。