How do I make a formatter for this `val pubDate = ...
# kotlinx-datetime
d
How do I make a formatter for this
val pubDate = "Sun, 12 Sep 2021 15:35:34 +0300"
? I'm posting my current attempt in the thread.
Copy code
val pubDateFormat = DateTimeComponents.Format {
    dayOfWeek(DayOfWeekNames.ENGLISH_ABBREVIATED)
    chars(", ")
    dayOfMonth()
    char(' ')
    monthName(MonthNames.ENGLISH_ABBREVIATED)
    char(' ')
    year()
    char(' ')
    hour(); char(':'); minute(); char(':'); second()
    offsetHours()
//    offsetMinutesOfHour()
}

pubDateFormat.parse(pubDate).toLocalDateTime()
I don't see how to parse the
+0300
...
r
have you tried without
char('+')
? I would assume it's already in the offset part.
d
yeah
I get a funny error (I fixed the above code), that it's finding a 2 instead of +
r
char(' ')
after
second()
perhaps?
d
Caused by: kotlinx.datetime.internal.format.parser.ParseException: Errors: position 29: 'There is more input to consume', position 12: 'Expected - but got 2', position 12: 'Expected + but got 2' at kotlinx.datetime.internal.format.parser.Parser.match-impl(Parser.kt:197) at kotlinx.datetime.internal.format.parser.Parser.match-impl$default(Parser.kt:186) at kotlinx.datetime.format.AbstractDateTimeFormat.parse(DateTimeFormat.kt:134) ... 37 more
Copy code
val pubDateFormat = DateTimeComponents.Format {
    dayOfWeek(DayOfWeekNames.ENGLISH_ABBREVIATED)
    chars(", ")
    dayOfMonth()
    char(' ')
    monthName(MonthNames.ENGLISH_ABBREVIATED)
    char(' ')
    year()
    char(' ')
    hour(); char(':'); minute(); char(':'); second(); char(' ')
    offsetHours()
//    offsetMinutesOfHour()
}
r
uncomment
offsetMinutesOfHour()
d
👍🏼 Yeah, it ended up being that char(' ') before the offsets that messed my previous tests up, thanks!
And in Kotlin notebook it gave me that funny error, whereas in playground it told me that there's more input left to parse...
But what's funny is that it doesn't seem to consider that offset...?
2021-09-12T153534Z
Copy code
pubDateFormat.parse(pubDate).toLocalDateTime().toInstant(TimeZone.UTC)
r
LocalDateTime doesn't have any offset.
d
So it just swallows it up?
Is there maybe a way to make an Instant out of that that does consider the time zone?
r
pubDateFormat.parse(pubDate).toInstantUsingOffset()
d
👍🏼 I hadn't noticed that one (the IDE doesn't always put that on the top of the list...), thanks!
d
Now after all that, it seems like I need to output this to a postgres date field with the
YYYY-MM-DD
format... what's the easiest way to do that from here?
It seems like format() on LocalDate doesn't take in a DateTimeComponents.Format....
Ok, I think I figured this out finally:
Copy code
val postgresDateFormat = LocalDate.Format {
        year(); char('-'); monthNumber(); char('-'); dayOfMonth()
    }

DateTimeComponents.Formats.RFC_1123.parse(pubDate!!)
        .toLocalDate().format(postgresDateFormat)
d