Kotlin:获取两个日期之间的差异(现在和上一个日期)

Hfr*_*rav 4 datetime date kotlin

抱歉,如果类似问题被问了太多次,但我找到的每个答案似乎都有一个或多个问题。

我有一个字符串形式的日期:例如:“04112005”

这是约会。2005 年 11 月 4 日。

我想获得当前日期和此日期之间的年数和天数差异。

到目前为止,我的代码获取年份并减去它们:

fun getAlderFraFodselsdato(bDate: String): String {
    val bYr: Int = getBirthYearFromBirthDate(bDate)
    var cYr: Int = Integer.parseInt(SimpleDateFormat("yyyy").format(Date()))

    return (cYr-bYr).toString()
}
Run Code Online (Sandbox Code Playgroud)

但是,自然而然,这是非常不准确的,因为不包括月份和日期。

我尝试了几种方法来创建 Date、LocalDate、SimpleDate 等对象,并使用它们来计算差异。但出于某种原因,我没有让他们中的任何一个工作。

我需要创建当前年、月和日的日期(或类似)对象。然后我需要从一个包含月份和年份(“04112005”)的字符串创建相同的对象。然后我需要得到这些之间的差异,以年、月和日为单位。

所有提示表示赞赏。

deH*_*aar 6

I would use java.time.LocalDate for parsing and today along with a java.time.Period that calculates the period between two LocalDates for you.
See this example:

fun main(args: Array<String>) {
    // parse the date with a suitable formatter
    val from = LocalDate.parse("04112005", DateTimeFormatter.ofPattern("ddMMyyyy"))
    // get today's date
    val today = LocalDate.now()
    // calculate the period between those two
    var period = Period.between(from, today)
    // and print it in a human-readable way
    println("The difference between " + from.format(DateTimeFormatter.ISO_LOCAL_DATE)
            + " and " + today.format(DateTimeFormatter.ISO_LOCAL_DATE) + " is "
            + period.getYears() + " years, " + period.getMonths() + " months and "
            + period.getDays() + " days")
}
Run Code Online (Sandbox Code Playgroud)

The output for a today of 2020-02-21 is

fun main(args: Array<String>) {
    // parse the date with a suitable formatter
    val from = LocalDate.parse("04112005", DateTimeFormatter.ofPattern("ddMMyyyy"))
    // get today's date
    val today = LocalDate.now()
    // calculate the period between those two
    var period = Period.between(from, today)
    // and print it in a human-readable way
    println("The difference between " + from.format(DateTimeFormatter.ISO_LOCAL_DATE)
            + " and " + today.format(DateTimeFormatter.ISO_LOCAL_DATE) + " is "
            + period.getYears() + " years, " + period.getMonths() + " months and "
            + period.getDays() + " days")
}
Run Code Online (Sandbox Code Playgroud)

  • @DeepakTripathi - 不再建议使用 Joda 时间。如果可能,使用 java.time.* (3认同)
  • 除了这个答案之外,您还可以使用 joda time。`持续时间(ReadableInstant 开始,ReadableInstant 结束)` (2认同)