Skip to content

Commit 032feef

Browse files
committed
Move partial date parsing logic to function
1 parent 719f62d commit 032feef

File tree

1 file changed

+30
-12
lines changed

1 file changed

+30
-12
lines changed

lib/src/main/kotlin/at/bitfire/vcard4android/contactrow/EventHandler.kt

Lines changed: 30 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -59,27 +59,45 @@ object EventHandler : DataRowHandler() {
5959
return null
6060
}
6161

62-
override fun handle(values: ContentValues, contact: Contact) {
63-
super.handle(values, contact)
64-
65-
var dateStr = values.getAsString(Event.START_DATE) ?: return
66-
val full: Temporal? = parseStartDate(dateStr)
67-
val partial: PartialDate? = if (full == null) try {
68-
if (dateStr.endsWith('Z')) {
62+
/**
63+
* Tries to parse a date string into a [PartialDate] object.
64+
* Returns the parsed [PartialDate] if successful, or `null` if parsing fails.
65+
*
66+
* Does some preprocessing to handle 'Z' suffix and strip nanoseconds, both not supported by
67+
* [PartialDate.parse].
68+
*
69+
* @param dateString The date string to parse.
70+
* @return The parsed [PartialDate] or `null` if parsing fails.
71+
*/
72+
internal fun parsePartialDate(dateString: String): PartialDate? {
73+
var dateString = dateString // to allow modification
74+
return try {
75+
if (dateString.endsWith('Z')) {
6976
// 'Z' is not supported for suffix in PartialDate, replace with actual offset
70-
dateStr = dateStr.removeSuffix("Z") + "+00:00"
77+
dateString = dateString.removeSuffix("Z") + "+00:00"
7178
}
7279

7380
val regex = "\\.\\d{3}".toRegex()
74-
if (dateStr.contains(regex)) {
81+
if (dateString.contains(regex)) {
7582
// partial dates do not accept nanoseconds, so strip them if present
76-
dateStr = dateStr.replace(regex, "")
77-
PartialDate.parse(dateStr)
83+
dateString = dateString.replace(regex, "")
84+
PartialDate.parse(dateString)
7885
} else {
79-
PartialDate.parse(dateStr)
86+
PartialDate.parse(dateString)
8087
}
8188
} catch (_: IllegalArgumentException) {
89+
// An error was thrown by PartialDate.parse
8290
null
91+
}
92+
}
93+
94+
override fun handle(values: ContentValues, contact: Contact) {
95+
super.handle(values, contact)
96+
97+
val dateStr = values.getAsString(Event.START_DATE) ?: return
98+
val full: Temporal? = parseStartDate(dateStr)
99+
val partial: PartialDate? = if (full == null) {
100+
parsePartialDate(dateStr)
83101
} else {
84102
null
85103
}

0 commit comments

Comments
 (0)