【问题标题】:Kotlin: Getting the difference betweeen two dates (now and previous date)Kotlin:获取两个日期之间的差异(现在和以前的日期)
【发布时间】:2020-06-05 20:37:53
【问题描述】:

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

我有一个字符串形式的日期:例如:“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()
}

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

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

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

感谢所有提示。

【问题讨论】:

  • 我建议你不要使用SimpleDateFormatDate。这些类设计不良且过时,尤其是前者,尤其是出了名的麻烦。相反,只需使用来自java.time, the modern Java date and time APILocalDate。正如答案所示,也不需要格式化和解析。

标签: date datetime kotlin


【解决方案1】:

我将使用 java.time.LocalDate 进行解析,todayjava.time.Period 一起为您计算两个 LocalDates 之间的时间段。
看这个例子:

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")
}

today2020-02-21 的输出是

The difference between 2005-11-04 and 2020-02-21 is 14 years, 3 months and 17 days

【讨论】:

  • 我除了这个答案你还可以使用joda time。 Duration(ReadableInstant start, ReadableInstant end)
  • @DeepakTripathi - 不再建议使用 Joda 时间。尽可能使用 java.time.*
  • 这是一个很好的解决方案,但在 26 API 级别以下不起作用,您应该试试这个stackoverflow.com/a/68997515/15005298
  • 嗯,现在有API DesugaringThreeTenABP 已经存在多年了。两者都为低于 26 的 Android API 启用了java.time
【解决方案2】:

它在 26 个 API 级别以下工作 日期格式太多,您只需输入日期格式以及所需的开始日期和结束日期。它会告诉你结果。如果需要,您只需看到不同的日期格式 harehere

tvDifferenceDateResult.text = getDateDifference(
                "12 November, 2008",
                "31 August, 2021",
                "dd MMMM, yyyy")

计算日期差的一般方法

fun getDateDifference(fromDate: String, toDate: String, formater: String):String{

        val fmt: DateTimeFormatter = DateTimeFormat.forPattern(formater)
        val mDate1: DateTime = fmt.parseDateTime(fromDate)
        val mDate2: DateTime = fmt.parseDateTime(toDate)
        val period = Period(mDate1, mDate2)
        // period give us Year, Month, Week and Days
        // days are between 0 to 6 
        // if you want to calculate days not weeks 
        //you just add 1 and multiply weeks by 7
        
        val mDays:Int = period.days + (period.weeks*7) + 1

        return "Year: ${period.years}\nMonth: ${period.months}\nDay: $mDays"
    }

【讨论】:

    猜你喜欢
    • 2020-02-06
    • 2020-03-22
    • 2017-03-27
    • 2019-04-24
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    相关资源
    最近更新 更多