MST

星途 面试题库

面试题:Kotlin日期时间处理库之复杂计算

给定一个Kotlin的日期对象,比如当前日期,计算出这个日期所在周的周一和周日的日期,并使用日期时间处理库完成日期之间的天数差计算。请写出完整代码实现。
25.3万 热度难度
编程语言Kotlin

知识考点

AI 面试

面试题答案

一键面试
import java.time.DayOfWeek
import java.time.LocalDate
import java.time.temporal.TemporalAdjusters

fun main() {
    // 获取当前日期
    val currentDate = LocalDate.now()

    // 计算所在周的周一
    val mondayOfWeek = currentDate.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY))
    // 计算所在周的周日
    val sundayOfWeek = currentDate.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY))

    // 计算周一和周日之间的天数差
    val daysBetween = java.time.temporal.ChronoUnit.DAYS.between(mondayOfWeek, sundayOfWeek)

    println("当前日期: $currentDate")
    println("所在周的周一: $mondayOfWeek")
    println("所在周的周日: $sundayOfWeek")
    println("周一和周日之间的天数差: $daysBetween")
}