I'm looking for a way to convert UTC date to LocalDateTime without limiting to API 26 (Android O) and above. Is there an alternate way to do this that will support API levels below API 26? I've currently got this and it works for devices running 26 and above:
@RequiresApi(Build.VERSION_CODES.O)
override fun convertUtcToLocalDateTime(utcVal: String): LocalDateTime {
return convertUtcToDate(utcVal).toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime()
}
override fun convertUtcToDate(utcDate: String): Date {
val formats = arrayListOf<String>(
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
"yyyy-MM-dd'T'HH:mm:ss.SS'Z'",
"yyyy-MM-dd'T'HH:mm:ss'Z'",
"yyyy-MM-dd'T'HH:mm:ss.SSS"
)
var date: Date? = null
formats.forEach {
if (date == null) {
try {
val parser = SimpleDateFormat(it, Locale.getDefault())
parser.timeZone = TimeZone.getTimeZone("UTC")
date = parser.parse(utcDate)
} catch (e: Exception) {
date = null
}
}
}
return date ?: Date()
}
Sample value that gets sent as utcVal
: 2021-09-05T13:55:35.097Z
Please let me know if theres an alternate that supports older APIs as well.