Skip to content

Instantly share code, notes, and snippets.

@GuilhE
Last active May 8, 2024 10:04
Show Gist options
  • Save GuilhE/13bc224f5c7d1e611566b97fba9351fb to your computer and use it in GitHub Desktop.
Save GuilhE/13bc224f5c7d1e611566b97fba9351fb to your computer and use it in GitHub Desktop.
Medium articles - What's Native
import kotlinx.cinterop.convert
import kotlinx.datetime.LocalDate
import platform.Foundation.NSCalendar
import platform.Foundation.NSDate
import platform.Foundation.NSDateComponents
import platform.Foundation.NSDateFormatter
import platform.Foundation.NSLocale
import platform.Foundation.currentLocale
//iosMain
internal actual class Platform actual constructor() {
actual fun formatDateTimeWithLocale(date: LocalDate, pattern: String): String {
return NSDateFormatter()
.apply {
dateFormat = pattern
locale = NSLocale.currentLocale
}
.stringFromDate(date.toNsDate() ?: throw IllegalStateException("Failed to convert LocalDate $date to NSDate"))
}
private fun LocalDate.toNsDate(): NSDate? {
val components = NSDateComponents()
components.year = this.year.convert()
components.month = this.monthNumber.convert()
components.day = this.dayOfMonth.convert()
return NSCalendar.currentCalendar.dateFromComponents(components)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment