Search code examples
javaandroidandroid-databinding

Android Databinding Formatter with org.threeten.bp.OffsetDateTime


I have an OffsetDateTime from the org.threeten:threetenbp package that I would like to format in my Android view.

I have a DTO:

public class SomeDto {
    private org.threeten.bp.OffsetDateTime timestamp;
    // getters and setters...
}

And a view with a binding and TextView:

<data>
    <variable
        name="dto"
        type="com.example.SomeDto" />
</data>
...
<TextView
        ...
        android:text="@{@string/formatTime(dto.timestamp)}"
 />

And a strings.xml:

<string name="formatTime">%1$tH:%1$tM</string>

But I can't seem to get it to work. I get:

 java.util.IllegalFormatConversionException: H != org.threeten.bp.OffsetDateTime

The Android docs detail the formatter here.

I can make the formatter work with strings. But no matter what date/time formatting I put in strings.xml, I get the above exception.

Does formatting simply not work with OffsetDateTime?


Solution

  • As @pskink commented on above, I used a BindingAdapter:

    @BindingAdapter("formatTime")
    public static void formatTime(TextView textView, OffsetDateTime dateTime) {
        textView.setText(dateTime.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM)));
    }
    

    And then in my view:

    <TextView
        ...
        formatTime="@{dto.timestamp}"
    />