-
Notifications
You must be signed in to change notification settings - Fork 110
DateTimeFormatter equivalent #211
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Have you seen the issues labeled with 'formatter'? |
You mean this?
Sorry but does that mean it is not yet supported? |
Yes. Regarding the Instant.parse(lowDate).toLocalDateTime(TimeZone.UTC) |
Thanks a lot, is there any alternative formatter we can use specially when working with KMM? |
@ArcherEmiya05 Because it is on the timeline, I ended up just writing a simple common shim for formatting/parsing which delegates to klock under the hood, since that library has a working multiplatform implementation. I'll be switching over as soon as this one also does. For pet projects at least, maybe this will also work for you. |
My usecase was very limited (and only needing to support Android & iOS) so I ended up just going for this very simple util, posting here incase it helps someone. In
|
On the basis of @SamCosta1 , I changed it again, and corrected the possible parameter errors. in common Main expect fun Instant.formatDate(pattern: String, defValue: String = ""): String
expect fun String.parseDate(pattern: String, defValue: Long = 0L): Long
fun Long.formatDate(pattern: String, defValue: String = ""): String {
return Instant.fromEpochMilliseconds(this).formatDate(pattern, defValue)
} in iosMain actual fun Instant.formatDate(pattern: String, defValue: String): String {
return try {
val dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = pattern
dateFormatter.stringFromDate(
toNSDate()
)
} catch (e: Exception) {
defValue
}
}
actual fun String.parseDate(pattern: String, defValue: Long): Long {
return try {
val dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = pattern
val result = dateFormatter.dateFromString(this)?.timeIntervalSince1970?.toLong()
if (result != null) {
result * 1000
} else {
defValue
}
} catch (e: Exception) {
defValue
}
} in JVM and Android: actual fun Instant.formatDate(pattern: String, defValue: String): String {
return try {
SimpleDateFormat(pattern).format(Date(this.toEpochMilliseconds()))
} catch (e: Exception) {
defValue
}
}
actual fun String.parseDate(pattern: String, defValue: Long): Long {
return try {
SimpleDateFormat(pattern).parse(this).time
} catch (e: Exception) {
defValue
}
} |
It is not included in the documentation so we would like to ask if Kotlinx Datetime has
java.time.format.DateTimeFormatter
equivalent for formatting?Here are the following usage we had with the Java
DateTimeFormatter
Currently using
coreLibraryDesugaringEnabled
for backward compatibility.The text was updated successfully, but these errors were encountered: