Alex
Alex

Reputation: 69

different Time Zones in android

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);

Upvotes: 2

Views: 166

Answers (2)

Basil Bourque
Basil Bourque

Reputation: 338855

tl;dr

Duration.between ( then , Instant.now() ) 

Details

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. For that, Instant class.

Instant then = Instant.now() ;
…
Instant now = Instant.now() ;

Duration class represents elapsed time on a scale of hours-minutes-seconds.

Duration d = Duration.between ( then , now ) ;

Notice that no time zones were involved.

Track your date-time values as java.time objects, not text. Generate text only as needed for logging, debugging, and presentation to the user.


The java.time classes are built into Android 26+. For earlier Android, the “desugaring” features in the latest tooling makes available most of the java.time functionality.

Upvotes: 4

SoftwareGuy
SoftwareGuy

Reputation: 1479

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.

Upvotes: 1

Related Questions