If you are building social network or chat app then this post is really helpful. Logic behind this thing is very simple when ever user post data we set time GMT to GMT 0 as shown below now when ever other user view post we first get his time zone and calculate time according to that zone and show. Please check comment where we do all this.


Calendar cal = Calendar.getInstance();
long milliDiff = cal.get(Calendar.ZONE_OFFSET);
// Getting time Zone
String[] ids = TimeZone.getAvailableIDs();
String name = null;
for (String id : ids) {
TimeZone tz = TimeZone.getTimeZone(id);
if (tz.getRawOffset() == milliDiff) {
// Found a match.
name = id;
break;
}
}
System.out.println(name);
//current date time According to GMT 00
Calendar call = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
Date currentLocalTime = call.getTime();
DateFormat date = new SimpleDateFormat("dd-MM-yyy HH:mm:ss");
date.setTimeZone(TimeZone.getTimeZone("GMT"));
String localTime = date.format(currentLocalTime);
System.out.println(localTime);
//current date time according to time zone
TimeZone tz = TimeZone.getTimeZone(name);
SimpleDateFormat destFormat = new SimpleDateFormat("dd-MM-yyy HH:mm:ss");
destFormat.setTimeZone(tz);
String result = destFormat.format(currentLocalTime);
System.out.println(result);
DateFormat dfm = new SimpleDateFormat("dd-MM-yyy HH:mm:ss");
try {
Date unixtime = dfm.parse(result);
Date NowDate = dfm.parse(localTime);
String timePassedString = String.valueOf(getRelativeTimeSpanString(NowDate.getTime(), unixtime.getTime(), DateUtils.MINUTE_IN_MILLIS));
System.out.println(timePassedString);
} catch (ParseException e) {
e.printStackTrace();
}

view raw

timeAgo.java

hosted with ❤ by GitHub

hope this help you 🙂