如何从Firestore获取指定数据并转换为字符串、日期等类型计算时间间隔
问题核心原因
你调用document.getData().toDate()报错的原因是:document.getData()返回的是Map<String, Object>类型的全量文档数据,toDate()是Firebase Timestamp类的专属方法,不能直接作用在Map对象上。
日期字段转换与间隔计算
Firestore的QueryDocumentSnapshot提供了专用的类型获取方法,无需手动从Map中取值再转换,避免类型转换异常:
for (QueryDocumentSnapshot document: task.getResult()) { // 直接用getDate获取日期字段,自动处理Firestore内部的Timestamp转Date逻辑 Date startDate = document.getDate("Starting date"); if (startDate == null) { // 字段不存在时的容错处理 continue; } // 1. 转成自定义格式的字符串展示 SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm", Locale.CHINA); String showDate = sdf.format(startDate); // 2. 计算至今的天数差 long nowMs = System.currentTimeMillis(); long diffMs = nowMs - startDate.getTime(); // 毫秒转天数,需要取整可以用Math.round等方法处理 long passedDays = diffMs / (1000 * 60 * 60 * 24); }
如果你坚持要用document.get()方法取值,可按以下方式做类型兼容:
Object dateRaw = document.get("Starting date"); Date startDate = null; // 兼容Firestore返回Timestamp或Date两种可能的情况 if (dateRaw instanceof com.google.firebase.Timestamp) { startDate = ((com.google.firebase.Timestamp) dateRaw).toDate(); } else if (dateRaw instanceof java.util.Date) { startDate = (java.util.Date) dateRaw; }
数值类型转换
和日期字段一样,直接用Snapshot提供的专用方法即可完成类型转换:
// 获取double类型字段 double quantification = document.getDouble("Quantification"); // 转int可按需处理精度 int quantificationInt = (int) Math.round(quantification); // 如果是整数类型字段,用getLong方法再转int int intValue = (int) document.getLong("你的整数字段名");
内容的提问来源于stack exchange,提问作者Tritize
相关产品推荐
相关产品推荐

