You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

消息收发时间显示时差3小时问题求助(附相关代码)

问题分析与解决方案

你的问题核心是Locale不影响时区设置——修改Locale只是改变日期时间的显示语言(比如月份名称、上午/下午的表述),但不会调整时区。时差3小时的原因是解析UTC时间戳时,Calendar使用了错误的时区,导致时间转换错误。

System.currentTimeMillis()获取的是UTC标准时间戳(从1970-01-01 UTC起的毫秒数),这个值本身是正确的。问题出在接收端解析时,没有将UTC时间戳转换为正确的本地时区。

修复方案

直接在解析时间时指定正确的时区(推荐使用用户本地时区,让用户看到自己当地的时间):

方法1:使用Calendar指定时区

修改AdapterChat中的代码:

// 获取设备本地时区
TimeZone localTZ = TimeZone.getDefault();
Calendar cal = Calendar.getInstance(localTZ, Locale.getDefault());
cal.setTimeInMillis(Long.parseLong(timeStamp));
String dateTime = DateFormat.format("dd/MM/yyyy hh:mm aa", cal).toString();

方法2:使用SimpleDateFormat更简洁处理

DateFormat.format()是旧API,推荐用SimpleDateFormat更清晰控制时区:

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm aa", Locale.getDefault());
// 设置为本地时区
sdf.setTimeZone(TimeZone.getDefault());
// 直接将时间戳转为Date后格式化
String dateTime = sdf.format(new Date(Long.parseLong(timeStamp)));

如果需要统一显示UTC时间(不推荐,用户体验差),可以将时区指定为UTC:

sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

额外说明

如果是跨地区聊天,无需额外传递时区信息——UTC时间戳是全球统一的,接收端只需要将其转换为自己的本地时区,就能显示正确的当地时间。

内容的提问来源于stack exchange,提问作者user23529806

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 13:35:03