Skip to content

Instantly share code, notes, and snippets.

@thomasstr
Created May 3, 2013 16:04
Show Gist options
  • Save thomasstr/5510396 to your computer and use it in GitHub Desktop.
Save thomasstr/5510396 to your computer and use it in GitHub Desktop.
// TimeAgo Variables
private static final int SECOND_MILLIS = 1000;
private static final int MINUTE_MILLIS = 60 * SECOND_MILLIS;
private static final int HOUR_MILLIS = 60 * MINUTE_MILLIS;
private static final int DAY_MILLIS = 24 * HOUR_MILLIS;
private static final long sAppLoadTime = System.currentTimeMillis();
private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
private static final String TIME_ZONE = "UTC";
@SuppressLint("SimpleDateFormat")
public String getTimeAgo(String jsonString, Context ctx) throws ParseException {
format = new SimpleDateFormat(DATE_FORMAT);
format.setTimeZone(TimeZone.getTimeZone(TIME_ZONE));
railsDate = new Date();
railsDate = format.parse(jsonString);
time = railsDate.getTime();
if (time < 1000000000000L) {
// if timestamp given in seconds, convert to millis
time *= 1000;
}
long now = getCurrentTime(ctx);
if (time > now || time <= 0) {
time = 0;
return null;
}
// TODO: localize
final long diff = now - time;
if (diff < MINUTE_MILLIS) {
return "akkurat nå";
} else if (diff < 2 * MINUTE_MILLIS) {
return "mindre enn ett minutt siden";
} else if (diff < 50 * MINUTE_MILLIS) {
return diff / MINUTE_MILLIS + " minutter siden";
} else if (diff < 90 * MINUTE_MILLIS) {
return "èn time siden";
} else if (diff < 24 * HOUR_MILLIS) {
return diff / HOUR_MILLIS + " timer siden";
} else if (diff < 48 * HOUR_MILLIS) {
return "i går";
} else {
return diff / DAY_MILLIS + " dager siden";
}
}
public static long getCurrentTime(final Context context) {
if (BuildConfig.DEBUG) {
return context.getSharedPreferences("mock_data", Context.MODE_PRIVATE)
.getLong("mock_current_time", System.currentTimeMillis())
+ System.currentTimeMillis() - sAppLoadTime;
} else {
return System.currentTimeMillis();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment