utc时间日期android,如何将UTC时间戳转换为android中的设备本地时间

这篇博客探讨了如何正确处理服务器返回的UTC时间戳,并与本地系统时间进行比较。通过使用Calendar和SimpleDateFormat,可以校验时间戳是否符合预期的日期,并计算时间差。如果服务器时间戳不是UTC,将会导致时间差异不准确。文章提供了调试和验证时间戳的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

您的示例中的代码乍一看看起来很好。顺便说一句,如果服务器时间戳是UTC(即它是一个纪元时间戳),那么你不必应用当前时区偏移量。换句话说,如果服务器时间戳是UTC格式,那么您可以简单地获取服务器时间戳和系统时间之间的差异(System.currentTimeMillis()),因为系统时间是UTC(纪元)。

我会检查来自服务器的时间戳是否符合预期。如果服务器的时间戳未转换为您期望的日期(在本地时区中),则时间戳与当前系统时间之间的差异将不是您所期望的。

使用Calendar获取当前时区。使用当前时区初始化SimpleDateFormatter;然后记录服务器时间戳并验证它是否是您期望的日期:

Calendar cal = Calendar.getInstance();

TimeZone tz = cal.getTimeZone();

/* debug: is it local time? */

Log.d("Time zone: ", tz.getDisplayName());

/* date formatter in local timezone */

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");

sdf.setTimeZone(tz);

/* print your timestamp and double check it's the date you expect */

long timestamp = cursor.getLong(columnIndex);

String localTime = sdf.format(new Date(timestamp * 1000)); // I assume your timestamp is in seconds and you're converting to milliseconds?

Log.d("Time: ", localTime);如果打印的服务器时间不是您所期望的,那么您的服务器时间不是UTC。

如果打印的服务器时间是您期望的日期,那么您不必将rawoffset应用于它。所以你的代码会更简单(减去所有调试日志记录):

long timestamp = cursor.getLong(columnIndex);

Log.d("Server time: ", timestamp);

/* log the device timezone */

Calendar cal = Calendar.getInstance();

TimeZone tz = cal.getTimeZone();

Log.d("Time zone: ", tz.getDisplayName());

/* log the system time */

Log.d("System time: ", System.currentTimeMillis());

CharSequence relTime = DateUtils.getRelativeTimeSpanString(

timestamp * 1000,

System.currentTimeMillis(),

DateUtils.MINUTE_IN_MILLIS);

((TextView) view).setText(relTime);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值