使用数据绑定时从getTimeInMillis获取日期

11

我有一个timeInMillis值,我知道可以通过类似以下方式获取Date;

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

我正在使用 DataBinding 来填充一个 RecyclerView。我也知道在使用 DataBinding 时可以像这样操作字符串;

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

然而,我无法弄清如何使用格式化的 Date 从我的 timeInMillis 值中填充 TextView


为什么不使用编程方式将dateString设置到你的TextView中?我还在研究数据绑定,不确定是否允许这样做。看起来你是想在XML中设置TextView的格式? - Adam Gardner
3个回答

33

我认为把格式放在资源中是最好的方法:

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

然后您可以像这样将值绑定到资源:

<TextView ... android:text="@{@string/format(model.date)}" />

干净,我喜欢它 - 谢谢! - Shazbot
3
好的回答。这里有文档,可以了解更多格式化选项(例如,我想要的格式是“2020年1月1日”,所以我使用了"%1$tb %1$td, %1$tY")。 - Chris Chute
有没有一种方法可以使用设备区域设置的时间格式? - Emil S.

18
你可以在你的模型中添加一个函数,使它能够将你的timeInMillis转换为格式化后的日期。
在你用于数据绑定布局的模型中:
public String getDateFormatted(){
    SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); 
    return formatter.format(new Date(dateInMillis)));;
}

在您的布局中:

<layout>
   <data>
      <variable name="yourModel"
                type="com.example.model.yourModel"/>
   </data>
...
<TextView 
...
   android:text="@{yourModel.dateFomatted}"
/>

0

正如George Mount所说,你可以使用本地字符串格式资源来处理它。

在这里,我展示了一些我最终实现的例子:

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

第一个是01/01/2000

第二个是00:00

所有文档都在这里


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接