很抱歉,如果问过太多类似的问题,但是我发现每个答案似乎都存在一个或多个问题。
我有一个字符串形式的日期:例如:“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””)中创建相同的对象。然后,我需要弄清年,月和日之间的差异。
所有提示表示赞赏。
最佳答案
我将使用java.time.LocalDate
进行解析,今天使用java.time.Period
来为您计算两个LocalDate
之间的时间间隔。
请参阅以下示例:
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")
}
today
的2020-02-21
的输出是The difference between 2005-11-04 and 2020-02-21 is 14 years, 3 months and 17 days
关于date - Kotlin:获取两个日期(现在和以前的日期)之间的差额,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60338248/