What could be wrong with this formatting code. The...
# compose-ios
r
What could be wrong with this formatting code. The same input for
format
works for JVM and Android but throws the exception on iOS
Copy code
actual fun LocalDate.format(format: String): String {
    val formatter = NSDateFormatter().apply { dateFormat = format }

    return formatter.stringFromDate(
        toNSDateComponents().date
            ?: throw IllegalStateException("Error converting Kotlin LocalDate to NSDate")
    )
}
👍 1
t
What is the format you are trying to use. It is possible it is not compatible with iOS, since the formats are not always the same cross platform.
r
I'm just using
dd.MM.yy
as the pattern. What I ended up doing is converting the date to an
Instant
and calling
toNSDate()
on it.
toNSDateComponents().date
keeps on returning null
Copy code
actual fun LocalDate.format(format: String): String {
    val formatter = NSDateFormatter().apply {
        dateFormat = format
        timeZone = TimeZone.currentSystemDefault().toNSTimeZone()
    }

    return formatter.stringFromDate(
        atStartOfDayIn(TimeZone.currentSystemDefault()).toNSDate()
    )
}
s
@Rafs any update on this?
r
Are you facing a similar problem @Shoaib khalid? This is how I solved it.
Copy code
actual fun LocalDate.format(format: String): String {
    val formatter = NSDateFormatter().apply {
        dateFormat = format
        timeZone = TimeZone.currentSystemDefault().toNSTimeZone()
    }

    return formatter.stringFromDate(
        atStartOfDayIn(TimeZone.currentSystemDefault()).toNSDate(),
    )
}
s
I've no't implemented anything yet. I was just looking around how can i format DateTime. would be great if you please share expect/actual for both platforms. thank you
r
This is how the expect looks like
expect fun LocalDate.format(format: String): String
s
Great, thanks buddy
r
For Android and JVM,
Copy code
actual fun LocalDate.format(format: String): String {
    return DateTimeFormatter.ofPattern(format).format(this.toJavaLocalDate())
}
s
@Rafs LocalDate isn't found.
with expect.
r
You need to import kotlinx datetime dependency
s
ahh in common main. right?
r
Yeah
1