Android Java 中如何更新“友好日期”显示?
结论
为了刷新“Today/Tomorrow”,不建议改 Firebase 里的时间戳,也不需要写 counter 或用 Cloud Function 触发刷新。保留 long 时间戳作为唯一数据源,每次绑定或刷新 RecyclerView 时,用设备当前日期重新计算友好文本即可。应用回到前台时刷新一次;如果页面可能跨午夜一直开着,再在下一个午夜定时刷新。20 条记录直接刷新整个列表成本很低。
为什么这样做
“Today/Tomorrow”只是按设备当前日期、时区和 Locale 算出来的显示文本。Firebase 里保存的 timestamp 不用变,变的是当前时间。所以这是 UI 层的刷新问题,和数据库同步无关。
你提到的三种方案:
- 遍历 RecyclerView 更新友好日期:思路对。不要从 View 上已有的文本反推日期,直接让 adapter 重新绑定或通知列表刷新。
- 更新 Firebase 记录里的 counter 来触发刷新:不推荐。会增加数据库写入,让其他客户端跟着同步,而且 counter 与本地日期显示没有直接关系。
- 用 Cloud Function 更新数据库 counter:更不推荐。会增加成本、延迟和部署复杂度,云端也很难准确代表每台设备的本地时区和午夜时间。
格式化方法
在 adapter 绑定数据时调用格式化方法,别缓存“Today/Tomorrow”字符串。例如:
private String formatNiceDate(long timestamp) {
ZoneId zone = ZoneId.systemDefault();
LocalDate target = Instant.ofEpochMilli(timestamp).atZone(zone).toLocalDate();
LocalDate today = LocalDate.now(zone);
long days = ChronoUnit.DAYS.between(today, target);
String prefix = "";
if (days == 0) prefix = "Today";
else if (days == 1) prefix = "Tomorrow";
else if (days == -1) prefix = "Yesterday";
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("EEE, dd MMM, yyyy", Locale.ENGLISH);
String date = target.format(fmt);
return prefix.isEmpty() ? date : prefix + " " + date;
}
然后在 onBindViewHolder 或你的 ViewHolder 绑定代码中调用:
holder.date.setText(formatNiceDate(note.getTimestamp()));
如果 minSdk 低于 26,需要在模块配置中启用 core library desugaring,或者改用 Calendar/SimpleDateFormat 实现。用 LocalDate 比较日期,比直接用毫秒除以一天更稳,能避开夏令时造成的 23/25 小时问题。
刷新时机
onResume() 能覆盖大多数“重新进入页面”的场景。你的原代码已经在 onResume() 里调用了 noteAdapter.notifyDataSetChanged(),这会让可见项重新绑定。如果希望页面一直停在前台、跨午夜也能自动变化,可以在下一个午夜加一次定时刷新:
private final Handler dateHandler = new Handler(Looper.getMainLooper());
private final Runnable dateRefreshRunnable = new Runnable() {
@Override
public void run() {
if (noteAdapter != null) {
noteAdapter.notifyDataSetChanged();
}
scheduleNextMidnightRefresh();
}
};
private void scheduleNextMidnightRefresh() {
dateHandler.removeCallbacks(dateRefreshRunnable);
Calendar next = Calendar.getInstance();
next.set(Calendar.HOUR_OF_DAY, 0);
next.set(Calendar.MINUTE, 0);
next.set(Calendar.SECOND, 0);
next.set(Calendar.MILLISECOND, 0);
next.add(Calendar.DAY_OF_MONTH, 1);
long delay = next.getTimeInMillis() - System.currentTimeMillis();
dateHandler.postDelayed(dateRefreshRunnable, Math.max(delay, 1000));
}
@Override
protected void onResume() {
super.onResume();
if (noteAdapter != null) {
noteAdapter.notifyDataSetChanged();
}
scheduleNextMidnightRefresh();
}
@Override
protected void onPause() {
super.onPause();
dateHandler.removeCallbacks(dateRefreshRunnable);
}
如果记录数量以后可能变大,可以改用 notifyItemRangeChanged(0, noteAdapter.getItemCount()) 做局部刷新,不必用 notifyDataSetChanged() 全量刷新。当前只有 20 条记录,全量刷新更简单。
注意事项
- 不要把“Today”这类展示文本写回 Firebase,免得展示层数据污染业务数据。
- 如果手机时区或系统时间被手动改过,
onResume()重新计算通常就能纠正;必要时再监听系统时间、时区变化后刷新。 Handler适合页面可见时跨午夜刷新;应用进入后台后不保证准点执行,但回到前台时onResume()会立即重新计算。- 如果以后需要后台每天生成通知,或跨设备同步“业务日期状态”,再考虑 Cloud Function 或后端任务;只是展示友好日期的话,不需要云端参与。
备注:内容仅供参考。
