Hello! I want to convert an ISO date format into a...
# compose-web
p
Hello! I want to convert an ISO date format into a given format. I'm doing it using JSJoda library as below:
Copy code
val date = LocalDateTime.parse(isoValue)
val dateFormat = DateTimeFormatter.ofPattern(format)
return date.format(dateFormat)
This is giving me an error which says that
DateTimeFormatter.ofPattern(format)
needs a Locale but I'm not getting any option to set Locale by doing something like
DateTimeFormatter.ofPattern(format).withLocale(Locale.ENGLISH)
because
Locale
is just an interface without any implementation. Tried googling but didn't find anything. Is there any other way to do this? TIA
1
r
If you want to use JSJoda, check out: https://js-joda.github.io/js-joda/manual/formatting.html
In my project I created an expect/actual for date/time formatting. My JS implementation uses
Date.toLocaleTimeString
and looks like this:
Copy code
actual fun formatDateTime(date: LocalDateTime, locale: String): String =
  jsFormatDateTime(date.year, date.monthNumber - 1, date.dayOfMonth, date.hour, date.minute, locale)

@Suppress("UNUSED_PARAMETER", "LongParameterList")
private fun jsFormatDateTime(yearArg: Int, monthArg: Int, dayArg: Int, hourArg: Int, minuteArg: Int, locale: String): String =
  js(
    "(new Date(yearArg, monthArg, dayArg, hourArg, minuteArg))" +
      ".toLocaleTimeString(locale, {year: 'numeric', month: 'short', day: '2-digit'});"
  ) as String
Where locale is just a standard locale string e.g.
en-US
.
l
FYI, you can do all of this in pure Kotlin using Klock (https://docs.korge.org/klock/). At least this worked well for me…
p
@Luc Girardin This works for me. Thank you! @rocketraman Thanks for showing a different approach
👍 1
r
Hopefully kotlinx-datetime will introduce formatting functions before long
yes black 1
761 Views