'How should I format and parse a DateTimeFormatter object?
I am trying to parse a date in parseServerTimeOffsetDateTime(), but I keep getting errors. Can't seem to make it work.
Here is what I have done so far:
For some reason the function keeps returning a Unit data type or TemporalAccessor if I try to parse the function with default
parsefunction. I tried converting it into a String or DataTimeFormatter and similar data types but in those cases it shows errors in try/catch block like a type missmatch and it won't compile.I checked in documentation but am still unclear what TemporalAccessor is.
I thought of writing my own parser
TimeParser, but I am not sure how I should implement it. Since the format of the date is2022-05-24T07:52:03ZI thought of putting 'T' and 'Z' as a character where it should be parsed.
private val serverTimeFormatterOffsetDateTimeFormatter =
DateTimeFormatter.ISO_ZONED_DATE_TIME
private val fallbackServerTimeFormatterOffsetDateTime =
DateTimeFormatter.ISO_ZONED_DATE_TIME
fun OffsetDateTime.toServerDateFormatOffsetDateTime() = DateTimeFormatter.ofPattern("yyyy-MM-dd")
fun OffsetDateTime.toServerTimeFormatOffsetDateTime() =
serverTimeFormatterOffsetDateTimeFormatter.format(this)
fun String.parseServerTimeOffsetDateTime() = try {
serverTimeFormatterOffsetDateTimeFormatter.TimeParser(this)
} catch (pe: ParseException) {
fallbackServerTimeFormatterOffsetDateTime.TimeParser(this)
}
fun DateTimeFormatter.TimeParser(time: String) {
// Haven't done anything yet here
val delimeter = "T"
val delimeter2 = "Z"
// code for parsing
}
How should I format and parse a DateTimeFormatter object?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
