【问题标题】:How to change date format using room?如何使用房间更改日期格式?
【发布时间】:2019-05-26 22:02:09
【问题描述】:

我正在使用 Room,我从 Firebase 实时数据库中检索其数据我有“请求”节点,其中包含日期节点代码工作正常但我想将日期格式更改为“dd-mm-yyyy” 我怎样才能做到这一点 ?

public class DateTypeConverter {
    @TypeConverter
    public static Date toDate(Long value) {
        if(null == value){
         return null;
        }else {
            Date date = new Date(value);
            return date;
        }
    }

    @TypeConverter
    public static Long toLong(Date value) {
        return value == null ? null : value.getTime();
    }
}

编辑: 我找到了解决方案here

我认为将格式放入资源中是最好的方法

【问题讨论】:

  • 在显示日期时是否要使用“dd-mm-yyyy”格式??
  • 是的,我也使用数据绑定

标签: android


【解决方案1】:
  1. 房间以long数据类型存储日期并以Date数据类型返回。

  2. 现在要显示此日期,您需要将其转换为“dd-mm-yyyy”格式的String

您可以通过在 Java 中使用 SimpleDateFormat 类来做到这一点。

public static String formatDate(Date date) {
        SimpleDateFormat dateFormat;
        // Apply desired format here
        dateFormat = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);

        Calendar c = Calendar.getInstance();
        dateFormat.setTimeZone(TimeZone.getDefault());
        c.setTimeInMillis(date.getTime());
        return dateFormat.format(c.getTimeInMillis());
    }

现在正如评论所说,您正在使用数据绑定,您可以在为 TextView 设置文本时直接调用此静态函数

希望对你有帮助!!!

【讨论】:

    猜你喜欢
    • 2018-03-27
    • 1970-01-01
    • 2015-12-27
    • 2016-10-20
    • 1970-01-01
    • 2022-11-02
    • 2012-06-03
    • 2019-05-01
    • 2018-02-22
    相关资源
    最近更新 更多