您的示例中的代码乍一看看起来很好。顺便说一句,如果服务器时间戳是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);