10

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.

1
  • Why not myTextView.setText(dateString) to your TextView programmatically? Still looking into Databinding, not sure if that is allowed or not. Looks like your trying to set format of the TextView in the XML? Mar 4, 2017 at 14:01

3 Answers 3

32

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)}" />
3
  • Clean, I like it - Thank you!
    – Shazbot
    May 1, 2019 at 15:17
  • 3
    Good answer. Here is the documentation for more options on formatting (e.g., I wanted a format like "Jan 1, 2020" so I used "%1$tb %1$td, %1$tY"). Jan 11, 2020 at 20:46
  • Is there some way of using this with the time format of the device's locale?
    – Emil S.
    Jun 2, 2020 at 12:08
17

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}"
/>
0

As George Mount said, you can use native string format resources to deal with it.

Here I show some examples I finally implemented:

<string name="formatter_date">%1$td/%1$tm/%1$tY</string>
<string name="formatter_time">%1$tH:%1$tM</string>

First is 01/01/2000

Second is 00:00

All the documentation is Here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.