Android Timestamp Get getRelativeTimeofTweet(String timeStamp)

Here you can find the source of getRelativeTimeofTweet(String timeStamp)

Description

Return an absolute timestamp such as "49 seconds ago"

Parameter

Parameter Description
timeStamp a parameter

Declaration

public static String getRelativeTimeofTweet(String timeStamp) 

Method Source Code

//package com.java2s;
import android.text.format.DateUtils;
import android.util.Log;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.HashMap;
import java.util.Locale;

public class Main {
    private static final String PARSE_TIMESTAMP_FORMAT = "EEE MMM dd HH:mm:ss ZZZZZ yyyy";

    /**//from www. ja  va2  s .  c  om
     * Return an absolute timestamp such as "49 seconds ago"
     * @param timeStamp
     * @return
     */
    public static String getRelativeTimeofTweet(String timeStamp) {

        final SimpleDateFormat sdf = new SimpleDateFormat(
                PARSE_TIMESTAMP_FORMAT, Locale.ENGLISH);
        String relativeTime = "";

        try {
            long dateInMillis = sdf.parse(timeStamp).getTime();

            relativeTime = getRelativeTimeAgo(dateInMillis);

        } catch (ParseException e) {
            Log.d("info", "Couldn't parse relative timestamp for: "
                    + timeStamp);
        }

        return relativeTime;
    }

    public static String getRelativeTimeAgo(long dateMillis) {
        String relativeDate = "";
        relativeDate = DateUtils.getRelativeTimeSpanString(dateMillis,
                System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS)
                .toString();

        HashMap<String, String> replaceMappings = new HashMap<String, String>();
        replaceMappings.put(" hours ago", "h");
        replaceMappings.put(" hour ago", "h");
        replaceMappings.put(" minutes ago", "m");
        replaceMappings.put(" minute ago", "m");
        replaceMappings.put(" seconds ago", "s");
        replaceMappings.put(" second ago", "s");
        replaceMappings.put(" day ago", "d");
        replaceMappings.put(" days ago", "d");
        replaceMappings.put("Yesterday", "1d");
        for (String suffixKey : replaceMappings.keySet()) {
            if (relativeDate.endsWith(suffixKey)) {
                relativeDate = relativeDate.replace(suffixKey,
                        replaceMappings.get(suffixKey));
            }
        }

        if (relativeDate.contains(",")) {
            int commaIndex = relativeDate.indexOf(",");
            relativeDate = relativeDate.substring(0, commaIndex);
        }

        return relativeDate;
    }
}

Related

  1. getFirstOfMonth(Timestamp t1)
  2. getFirstOfYear(Timestamp t1)
  3. getFriendlyTimeStamp()
  4. getLastOfMonth(Timestamp t1)
  5. getLastOfYear(Timestamp t1)
  6. getTimestamp(Timestamp timestamp, int day, int hour, int minute)
  7. getWeekOfYear(Calendar cal, Timestamp ts)
  8. getTimeStamp()
  9. getTimestamp(Context context)