简体   繁体   中英

Convert Date String to Date object in Kotlin? How to calculate number of days between today and specific date in Kotlin?

Part 1: I have date as string in the following format: "2020-10-15T22:54:54Z" I have to convert it into date object. Tried the following:

val dateString = "2020-10-15T22:54:54Z"
val dateFormatter = DateTimeFormatter.ofPattern("%Y-%m-%dT%H:%M:%SZ")
val updatedAtDate = LocalDate.parse(dateString, dateFormatter)
val today = LocalDateTime.now()
println("Updated At: $updatedAtDate")

Gives the following error: "Unknown pattern letter: T"

Part 2: Once I have the date object from above, I have to calculate the difference between today (Current Date) and the above date. How to do it in Kotlin?

tl;dr You don't need to create a custom formatter…

… for the val dateString = "2020-10-15T22:54:54Z" here, it is formatted in an ISO standard. Therefore, you can simply do this (if you want a LocalDate , just year, month and day):

val thatDate: LocalDate = OffsetDateTime.parse(dateString).toLocalDate()

Fully adressing all the aspects of your post:

You can utilize a java.time.Period.between(LocalDate, LocalDate) in order to calculate the difference between two LocalDate s. You only have to make sure the older date is the first argument, otherwise you will get a negative result. Here's a full example:

import java.time.OffsetDateTime
import java.time.LocalDate
import java.time.Period

fun main(args: Array<String>) {
    val dateString = "2020-10-15T22:54:54Z"
    // create an OffsetDateTime directly
    val thatDate = OffsetDateTime.parse(dateString)
                                      // and extract the date
                                      .toLocalDate()
    // get the current day (date only!)
    val today = LocalDate.now()
    // calculate the difference in days and make sure to get a positive result
    val difference = if (today.isBefore(thatDate))
                        Period.between(today, thatDate).days
                     else
                         Period.between(thatDate, today).days
    // print something containing both dates and the difference
    println("[$today] Updated At: $thatDate, difference: $difference days")
}

Output at Dec 10, 2021:

[2021-12-10] Updated At: 2020-10-15, difference: 25 days

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM