Skip to content

Instantly share code, notes, and snippets.

@nesquena
Last active September 29, 2021 16:35
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save nesquena/f786232f5ef72f6e10a7 to your computer and use it in GitHub Desktop.
Save nesquena/f786232f5ef72f6e10a7 to your computer and use it in GitHub Desktop.
Code for parsing a relative twitter date
// getRelativeTimeAgo("Mon Apr 01 21:16:23 +0000 2014");
public String getRelativeTimeAgo(String rawJsonDate) {
String twitterFormat = "EEE MMM dd HH:mm:ss ZZZZZ yyyy";
SimpleDateFormat sf = new SimpleDateFormat(twitterFormat, Locale.ENGLISH);
sf.setLenient(true);
String relativeDate = "";
try {
long dateMillis = sf.parse(rawJsonDate).getTime();
relativeDate = DateUtils.getRelativeTimeSpanString(dateMillis,
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS).toString();
} catch (ParseException e) {
e.printStackTrace();
}
return relativeDate;
}
@jaysondc
Copy link

Consider adding the "DateUtils.FORMAT_ABBREV_RELATIVE" flag to abbreviate "minutes ago" to "min. ago".

@tejen
Copy link

tejen commented Jul 1, 2020

Or, to use abbreviations like "5m" and "3d" instead of "5 minutes ago" and "3 days ago", check this out:

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;

public String getRelativeTimeAgo(String rawJsonDate) {
    String twitterFormat = "EEE MMM dd HH:mm:ss ZZZZZ yyyy";
    SimpleDateFormat sf = new SimpleDateFormat(twitterFormat, Locale.ENGLISH);
    sf.setLenient(true);

    try {
        long time = sf.parse(rawJsonDate).getTime();
        long now = System.currentTimeMillis();

        final long diff = now - time;
        if (diff < MINUTE_MILLIS) {
            return "just now";
        } else if (diff < 2 * MINUTE_MILLIS) {
            return "a minute ago";
        } else if (diff < 50 * MINUTE_MILLIS) {
            return diff / MINUTE_MILLIS + " m";
        } else if (diff < 90 * MINUTE_MILLIS) {
            return "an hour ago";
        } else if (diff < 24 * HOUR_MILLIS) {
            return diff / HOUR_MILLIS + " h";
        } else if (diff < 48 * HOUR_MILLIS) {
            return "yesterday";
        } else {
            return diff / DAY_MILLIS + " d";
        }
    } catch (ParseException e) {
        Log.i(TAG, "getRelativeTimeAgo failed");
        e.printStackTrace();
    }

    return "";
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment