Home > Software engineering >  How to Convert DateTime String to UTC format in Kotlin
How to Convert DateTime String to UTC format in Kotlin

Time:10-11

I have a problem where I am given a DateTime String which is assumed to be UTC -

2022-07-03T11:42:01

My task is to convert it to a UTC formatted string like this -

yyyy-MM-dd'T'HH:mm:ss'Z'

So it should appear like this -

2020-07-03T11:42:01.000Z

Here is my attempt so far -

import java.text.SimpleDateFormat
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.ZoneOffset
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
import java.util.Locale
import java.util.TimeZone

fun main() {
    val myDateTimeString = "2022-04-24T20:39:47"
    val ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
    val utc = TimeZone.getTimeZone("UTC");
    var isoFormatter =  SimpleDateFormat(ISO_FORMAT);
    isoFormatter.setTimeZone(utc);
    println(isoFormatter.format(myDateTimeString).toString())
}

I've played around with a few variations but I'm getting the following exception -

> Exception in thread "main" java.lang.IllegalArgumentException: Cannot format given Object as a Date
 at java.text.DateFormat.format (:-1) 
 at java.text.Format.format (:-1) 
 at FileKt.main (File.kt:22) 

Can anybody help?

Thanks :)

Link to my example in the Kotlin Playground - My Example

CodePudding user response:

You have java.time, that means you can have the desired result with just a few lines of code.

The following steps should do:

  • parse the input String to a LocalDateTime, which is specifically suitable for this step, because it stores only date and time of day, explicitly no offset or zone
  • append the desired ZoneOffset, here simply ZoneOffset.UTC
  • define a DateTimeFormatter for your desired output format (or use a built-in one, try them all)
  • print (or return) the result, which is then of type OffsetDateTime

Example:

fun main() {
    val input = "2022-07-03T11:42:01"
    // parse it to a LocalDateTime (date & time without zone or offset)
    val offsetDateTime: OffsetDateTime = LocalDateTime.parse(input)
                                                      // and append the desired offset
                                                      .atOffset(ZoneOffset.UTC)
    // define a formatter for your desired output
    val formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSX",
                                                Locale.ENGLISH)
    // and use it in order to print the desired result
    println("$input --> ${offsetDateTime.format(formatter)}")
}

Output of the example:

2022-07-03T11:42:01 --> 2022-07-03T11:42:01.000Z
  • Related