my application saves local time using OnStart() method and i am using this code below to convert time to "time ago" but when two persons from different time zones this method does not work it always shows incorrect time ago
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);
CodePudding user response:
You are using terrible date-time classes that were years ago supplanted by the modern java.time classes.
Use an offset from UTC of zero hours-minutes-seconds when capturing a moment.
Instant then = Instant.now() ;
…
Instant now = Instant.now() ;
Duration
class represents elapsed time.
Duration d = Duration.between ( then , now ) ;
Notice that no time zones were involved.
CodePudding user response:
When you store the time, you need to store in UTC. Retrieve it from server in UTC format. While displaying last seen , convert it to local time zone of that displaying device.