Home > Software design >  how convert GMT date String into Date
how convert GMT date String into Date

Time:06-10

I have a GMT String "Thr, 09 Jun 2022 19:20:00 GMT"

I want to convert this into Date.

Can anyone help how I convert this?

I tried every way but giving Unparseable date: "Thr, 09 Jun 2022 19:20:00 GMT"

Here is the code:

private fun getDate(time: String): Date? {
    val pattern = "EEE, dd MMM yyyy HH:mm:ss Z"
    val format = SimpleDateFormat(pattern)
    var javaDate: Date? = null
    try {
        javaDate = format.parse(time)
    } catch (e: ParseException) {
        e.printStackTrace()
    }
    return javaDate

}

I referred to this question.

CodePudding user response:

In case you decide not to use outdated libraries, you may want to take a look at java.time. There's a kotlinx.datetime currently under development, but it is based on java.time anyway.

You could parse your String like this:

import java.time.format.DateTimeFormatter
import java.time.ZonedDateTime
import java.util.Locale

fun main() {
    // your example
    val input = "Thu, 09 Jun 2022 19:20:00 GMT"
    // define a formatter that parses Strings like yours
    val dtf = DateTimeFormatter.ofPattern("EEE, dd MMM uuuu HH:mm:ss O",
                                          Locale.ENGLISH)
    // parse the String and get a ZonedDateTime
    val zdt = ZonedDateTime.parse(input, dtf)
    // print the result using the ISO format
    println(zdt.format(DateTimeFormatter.ISO_ZONED_DATE_TIME))
    // or print it using the formatter that parsed your example
    println(zdt.format(dtf))
}

This code outputs two lines:

2022-06-09T19:20:00Z
Thu, 09 Jun 2022 19:20:00 GMT

I suggest you make your fun return a java.time.ZonedDateTime

CodePudding user response:

The site answer you're referring to just works.

import java.text.*

fun main() {
    val rfcDate = "Sat, 13 Mar 2010 11:29:05 -0800";
    val pattern = "EEE, dd MMM yyyy HH:mm:ss Z";
    val format = SimpleDateFormat(pattern);
    val javaDate = format.parse(rfcDate);
    println(javaDate)
}

You can run the example online over here

So it's likely that your input string doesn't match such pattern.

And indeed Thr is not valid. It should be Thu. Here's the updated playground

CodePudding user response:

checking your pattern on enter link description here , seems to me you need change it from:

val pattern = "EEE, dd MMM yyyy HH:mm:ss Z";

to:

val pattern = "EEE, dd MMM yyyy HH:mm:ss z";
  • Related