genespos
genespos

Reputation: 3311

LocalDate to string format with HH:mm

I have a Kotlin code that retrives date (in text field) from SQLite DB and put it into a LocalDate variable (pill.startDay) from whom I show the date as below

val dtf: DateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu", Locale.ITALY)
val startDayStr: String =dtf.format(pill.startDay)
holder.tvStartDate.text = "Start: $startDayStr"

Now I need to show also hours and minutes but I've tryed many patterns (like "dd/MM/uuuu HH:mm" or "dd/MM/uuuu'T'HH:mm" or "dd/MM/uuuu HH:mm z") without success (the app always crashes)

The full data class is:

data class Pill(val id: Int,
                val pillName: String,
                val yesDays: Int,
                val pauseDays: Int = 0,
                val startDay: LocalDate = LocalDate.now())

The error is:

FATAL EXCEPTION: main Process: com.example.mytestapp, PID: 24087 java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: HourOfDay

Upvotes: 3

Views: 43

Answers (2)

Berk Berber
Berk Berber

Reputation: 382

You are getting UnsupportedTemporalTypeException because you have defined your data with LocalDate. LocalDate doesn't have any information about the time and once you are trying to convert it to time, it causes a crash.

You need to update your data class Pill to have LocalDateTime instead of LocalDate:

data class Pill(
    val id: Int,
    val pillName: String,
    val yesDays: Int,
    val pauseDays: Int = 0,
    val startDay: LocalDateTime = LocalDateTime.now()
)

Upvotes: 4

deHaar
deHaar

Reputation: 18558

The reason you cannot print hours of day, minutes of hour and further down the scala is that a LocalDate exclusively stores information about day of month, month of year and year.

What you need seems to be a LocalDateTime, which is combined from a LocalDate and a LocalTime.

Upvotes: 3

Related Questions