Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

580
Views
Correct way to parse Date in Kotlin Android (Minimum Android Version 21). My parse is not working

I want to parse this date in this format 2021-11-03T14:09:31.135Z (message.created_at)

My code is this:

val dateFormat = SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS")
var convertedDate = Date()
try {
    convertedDate = dateFormat.parse(message.created_at)
} catch (e: ParseException) {
    e.printStackTrace()
}

It is failing to parse

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Don't use SimpleDateFormat it's long outdated and troublesome.
Use DateTimeFormatter to parse the date.

 fun parseDate() {
        var formatter: DateTimeFormatter? = null
        val date = "2021-11-03T14:09:31.135Z" // your date string
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX") // formatter
            val dateTime: ZonedDateTime = ZonedDateTime.parse(date, parser) // date object
            val formatter2: DateTimeFormatter =
                DateTimeFormatter.ofPattern("EEEE, MMM d : HH:mm") // if you want to convert it any other format
            Log.e("Date", "" + dateTime.format(formatter2))
        }
    }

Output: Wednesday, Nov 3 : 14:09

To use this below android 8 , use desugaring

over 4 years ago · Santiago Trujillo Report

0

Well, the format not entirely what the string looks like:

  • You have a space instead of the T literal between the date and the time
  • You have no offset notation at the end
  • You are using hh, which is 12-hour format. Use HH instead.

This format should do it:

yyyy-MM-dd'T'HH:mm:ss.SSSX

However, note that Date and SimpleDateFormat are obsolete and troublesome. Use java.time instead. If your Android API level appears to be too low, you could use ThreeTen Backport.

over 4 years ago · Santiago Trujillo Report

0

If your minimum API level is 21, you can use API Desugaring, find some nice explanations about it here.

As soon as you have enabled API Desugaring, you can directly parse your ISO String to an OffsetDateTime:

val convertedDate = OffsetDateTime.parse(message.created_at)
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!