Kolos
Kolos

Reputation: 411

In Java (or Kotlin) I need to convert date and time from yyyy-mm-dd and hh:mm:ss format to LocalDate LocalTime using time zone

I need to convert Strings coming from JSON file to LocalDate and LocalTime formats using timeZone as string. I only managed to convert date to LocalDate using LocalDate.ofInstant(Instant, ZoneId) method, but it requires time and date format like so 2021-05-21T10:17:55.539729Z, but Strings I receive only are coming in the format as shown below (yyyy-mm-dd and hh:mm:ss)

{
"timeZone": "America/New_York",
"date": "2021-02-25",
"time": "13:00:00"
}

Upvotes: 1

Views: 302

Answers (1)

Lino
Lino

Reputation: 19910

You can just convert each of the subcomponents to their corresponding java.time object, and then combine all into a ZonedDateTime

val jsonData = // your parsed json
val zone = ZoneId.of(jsonData.timeZone)
val time = LocalTime.parse(jsonData.time)
val date = LocalDate.parse(jsonData.date)
val zonedDateTime = ZonedDateTime.of(date, time, zone)

println(zonedDateTime) // 2021-02-25T13:00-05:00[America/New_York]

Upvotes: 5

Related Questions