So, I know this is a problem well discussed upon and a lot of questions and answers (mostly concerning Joda) and also with the new class DateTimeFormatter and all that supports api levels above 26. But my concern is this:
- My android application supports 21 and above
- I get multiple variations of date/time formats of ISO-8601 from different APIs: for eg: a) “2020-09-03T17:03:11.719566Z” b) “2021-03-05T18:30:00Z”
So, I require to find #days between today and that date. When I write the code to parse one of them the other hits my catch block and vice versa, so I write a nested try/catch block to handle both the cases...something like this:
fun getFormattedDate(stringDate: String?): Long {
if (dueDateString.isNullOrEmpty())
return 0
val today = Calendar.getInstance().time
try {
val inputFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH)
val date = inputFormat.parse(dueDateString)
return if (date != null) {
val dueCalendar = Calendar.getInstance()
dueCalendar.time = date
getNoOfDays(today.time, dueCalendar.timeInMillis)
} else
0
} catch (ex: Exception) {
ex.showLog()
try {
val inputFormat1 = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH)
val date = inputFormat1.parse(dueDateString)
return if (date != null) {
val dueCalendar = Calendar.getInstance()
dueCalendar.time = date
getNoOfDays(today.time, dueCalendar.timeInMillis)
} else
0
} catch (exc: Exception) {
exc.showLog()
return 0
}
}
}
I am using this function to find #days between two dates:
fun getDueDateAfterParsing(dueDateString: String?): Long {
val today = ZonedDateTime.ofInstant(now(), ZoneId.systemDefault())
val dueDate = ZonedDateTime.parse(
dueDateString,
DateTimeFormatter.ISO_OFFSET_DATE_TIME.withZone(ZoneId.systemDefault())
)
return ChronoUnit.DAYS.between(today, dueDate)
}
I am pretty sure that the solution to this cannot be this complex. There are so many formats for ISO-8601 so i cant be writing try/catch blocks that fits for all cases right? So can anybody help me with the most simplest way I can get my way through this?
I have thought about regex too and most of them will end up saying Joda I am guessing, but at-least I want to be sure about what is the most optimal way or the best way of doing this.
Thanks in advance for any help.