0

Hello Devs,

I'm working on barcode scanner app, I get date and time at this pattern "20220610T230000Z" I think its ISO8601 date-time format However, I just want to parse this pattern so I can customize it as I want.

I tried this one:

val isoDate="20220610T230000Z" // from my barcode scanner
val df=SimpleDateFormat("yyyymmdd'T'HH:mm:ss.SSS'Z'")
val date= df.parse("20220610T230000Z")

but when i run code i get

java.text.parseexception unparseable

Thanks in advance

ADM
  • 20,406
  • 11
  • 52
  • 83
Ahmed Saad
  • 13
  • 7
  • Consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends. Use [desugaring](https://developer.android.com/studio/write/java8-support-table) in order to use [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). It is so much nicer to work with. `DateTimeFormatter.ofPattern("uuuuMMdd'T'HHmmssX").parse("20220610T230000Z", Instant::from)` yields an `Instant` of `2022-06-10T23:00:00Z`. – Ole V.V. Jun 27 '22 at 06:02
  • I replaced `"uuuuMMdd'T'HHmmssX"` with this pattern`"yyyyMMdd'T'HHmmss"` cause it needs API 24 and i target API 21. Whatever it works well with me. how can i accept your comment as an answer? thanks @OleV.V. – Ahmed Saad Jun 28 '22 at 15:01

2 Answers2

0

isoDate doesn't have any colons or periods in it. Since you're trying to turn isoDate into a Date object, you want something more like:

 val df=SimpleDateFormat("yyyymmdd'T'HHmmssSSS'Z'")

Then, if you want to output a date String with different formatting, you'll have to create a different SimpleDateFormat instance (let's call it dt2) with the intended formatting, and call dt2.format(date). See here for a full example.

Gavin Wright
  • 3,124
  • 3
  • 14
  • 35
  • still get Caused by: java.text.ParseException: Unparseable date: "20220610T230000Z", problem in that line -> val date= df.parse("20220610T230000Z") i think this (yyyymmdd'T'HHmmssSSS'Z') is not the right pattern for my coversion – Ahmed Saad Jun 28 '22 at 13:55
  • Oh yeah, you want to get rid of the "SSS" part. – Gavin Wright Jun 28 '22 at 14:51
  • still new in dates don't know what rid and what SSS but i just wanted to format this one then i can customize it i want and i solved it with this pattern `"yyyyMMdd'T'HHmmss"` – Ahmed Saad Jun 29 '22 at 00:28
0

My issue solved Thanks @OleV.V.

Solution This pattern: "yyyyMMdd'T'HHmmss"

Ahmed Saad
  • 13
  • 7