Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Date from getTimeInMillis when using Databinding

I have a timeInMillis value, which I know I can get a Date from with something like;

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); 
String dateString = formatter.format(new Date(dateInMillis)));

I'm using DataBinding to populate a RecyclerView. I am also aware that I can manipulate strings when using DataBinding with something like this;

android:text='@{String.format("%.1f", example.double)}'

However, I cannot work out how to populate the TextView with a formatted Datefrom my timeInMillis value.

like image 281
Jonny Wright Avatar asked Mar 04 '17 13:03

Jonny Wright


People also ask

When should I use databinding?

Data Binding allows you to effortlessly communicate across views and data sources. This pattern is important for many Android designs, including model view ViewModel (MVVM), which is currently one of the most common Android architecture patterns.

What is data binding in Kotlin?

The Data Binding Library is a support library that allows you to bind UI components in your layouts to data sources in your app using a declarative format rather than programmatically. Layouts are often defined in activities with code that calls UI framework methods.


2 Answers

You can add in your model a function which it can transform your timeInMillis to a formatted Date.

In your model used in dataBinding layout :

public String getDateFormatted(){
    SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); 
    return formatter.format(new Date(dateInMillis)));;
}

In your layout :

<layout>
   <data>
      <variable name="yourModel"
                type="com.example.model.yourModel"/>
   </data>
...
<TextView 
...
   android:text="@{yourModel.dateFomatted}"
/>
like image 122
BenjaminBihr Avatar answered Oct 20 '22 14:10

BenjaminBihr


I think that putting the format in resources is best approach:

<string name="format">%1$td/%1$tm/%1$tY</string>

And you would bind the value to the resource like this:

<TextView ... android:text="@{@string/format(model.date)}" />
like image 38
George Mount Avatar answered Oct 20 '22 14:10

George Mount