Home > OS >  How to parse date "2022-07-18T08:24:18Z" in android
How to parse date "2022-07-18T08:24:18Z" in android

Time:08-02

I have tried these format but none worked.

  1. yyyy-MM-dd'T'HH:mm:ss'Z'
  2. yyyy-MM-dd'T'HH:mm:ssZ
  3. yyyy-MM-dd'T'HH:mm:ssZZ
  4. yyyy-MM-dd'T'HH:mm:ss

Also tried "ZonedDateTime", but it is not available below Android O.

CodePudding user response:

If your minSDK is 25 or lower you have to use Java 8 API desugaring support to be able to use the java.time package from Java 8.

With that enabled you can simply use e.g.

OffsetDateTime.parse("2022-07-18T08:24:18Z")
ZonedDateTime.parse("2022-07-18T08:24:18Z")

(you can find many resources about the differences of these date formats).

CodePudding user response:

You can do it like this

fun parseDate(
        inputDateString: String?,
        inputDateFormat: SimpleDateFormat,
        outputDateFormat: SimpleDateFormat
    ): String? {
        var date: Date? = null
        var outputDateString: String? = null
        try {
            date = inputDateFormat.parse(inputDateString)
            outputDateString = outputDateFormat.format(date)
        } catch (e: ParseException) {
            e.printStackTrace()
        }
        return outputDateString
    }
  • inputString will be your Date, ex:"2022-07-18T08:24:18Z"
  • inputDateFormat : SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US)
  • outputDateFormat : in whichever format you want to show the date

I hope you get your answer from this

  • Related