我的应用程序使用OnStart()方法节省本地时间,我正在使用下面的代码将时间转换为“时间前”,但是当来自不同时区的两个人无法工作时,它总是显示不正确的时间。
private void updateUserStatus(String state)
{
String lastSeenTime;
Calendar calendar = Calendar.getInstance(Locale.ENGLISH);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
lastSeenTime = dateFormat.format(calendar.getTime());
HashMap<String,Object> onlineStatemap = new HashMap<>();
onlineStatemap.put("lastSeen", lastSeenTime);
onlineStatemap.put("state", state);
if (firebaseUser != null )
{
currentUserID = firebaseAuth.getCurrentUser().getUid();
RootRef.child("Users").child(currentUserID).child("userState").updateChildren(onlineStatemap);
}
}
private String calculateTime(String lastSeenTT)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
try {
long time = sdf.parse(lastSeenTT).getTime();
long now = System.currentTimeMillis();
CharSequence ago =
DateUtils.getRelativeTimeSpanString(time, now, DateUtils.MINUTE_IN_MILLIS);
return ago+"";
} catch (ParseException e) {
e.printStackTrace();
}
return "";
}
String timeAgo = calculateTime(lastSeenTT);发布于 2022-10-21 18:15:06
tl;dr
Duration.between ( then , Instant.now() ) 详细信息
您使用的是几年前被现代java.time类取代的糟糕的日期时间类。
在捕捉一个瞬间时,使用从世界协调时的零小时-分钟-秒的偏移量。为此,Instant课。
Instant then = Instant.now() ;
…
Instant now = Instant.now() ;Duration类以小时-分钟-秒的比例表示经过的时间。
Duration d = Duration.between ( then , now ) ;注意,没有涉及时区。
将日期时间值跟踪为java.time对象,而不是文本.只在需要时生成文本,以便向用户记录、调试和表示。
java.time类被内置到Android 26+中。对于早期的安卓来说,最新工具中的“去凝”功能使得大多数java.time功能都可用。
发布于 2022-10-21 18:10:37
当您存储时间时,您需要存储在UTC。以UTC格式从服务器检索它。在显示最后一次显示时,将其转换为显示设备的本地时区。
https://stackoverflow.com/questions/74157506
复制相似问题