Converts Facebook time to more readable format. E.g "5 minutes ago", "1 hour ago" or "February 28, 2018 at 14:35". - Android java.util

Android examples for java.util:Date Time

Description

Converts Facebook time to more readable format. E.g "5 minutes ago", "1 hour ago" or "February 28, 2018 at 14:35".

Demo Code

import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.style.URLSpan;
import android.text.util.Linkify;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Main{

    /**//from   w  w w  . j  a  v  a 2s .co m
     * Converts Facebook time to more readable format. E.g "5 minutes ago",
     * "1 hour ago" or "February 20, 2010 at 14:35".
     * 
     * @param fbTime
     *            String presentation of Facebook time.
     * @return Converted String.
     */
    public static final String convertFBTime(String fbTime) {
        String ret;
        try {
            SimpleDateFormat fbFormat = new SimpleDateFormat(
                    "yyyy-MM-dd'T'HH:mm:ssZ");
            Date eventTime = fbFormat.parse(fbTime);
            Date curTime = new Date();

            long diffMillis = curTime.getTime() - eventTime.getTime();
            long diffSeconds = diffMillis / 1000;
            long diffMinutes = diffMillis / 1000 / 60;
            long diffHours = diffMillis / 1000 / 60 / 60;
            if (diffSeconds < 60) {
                ret = diffSeconds + " seconds ago";
            } else if (diffMinutes < 60) {
                ret = diffMinutes + " minutes ago";
            } else if (diffHours < 24) {
                ret = diffHours + " hours ago";
            } else {
                String dateFormat = "MMMMM d";
                if (eventTime.getYear() < curTime.getYear()) {
                    dateFormat += ", yyyy";
                }
                dateFormat += "' at 'kk:mm";

                SimpleDateFormat calFormat = new SimpleDateFormat(
                        dateFormat);
                ret = calFormat.format(eventTime);
            }
        } catch (Exception ex) {
            ret = "error: " + ex.toString();
        }
        return ret;
    }

}

Related Tutorials