Android Long to Date Convert getRelativeTimeFromMilliSeconds(long dateInMillis)

Here you can find the source of getRelativeTimeFromMilliSeconds(long dateInMillis)

Description

get Relative Time From Milli Seconds

Declaration

public static String getRelativeTimeFromMilliSeconds(long dateInMillis) 

Method Source Code

//package com.java2s;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.text.format.DateUtils;
import android.util.Log;

public class Main {
    public static String getRelativeTimeFromMilliSeconds(long dateInMillis) {

        final String relativeTime = DateUtils.getRelativeTimeSpanString(
                dateInMillis, System.currentTimeMillis(),
                DateUtils.SECOND_IN_MILLIS).toString();
        return formatRelativeTime(relativeTime);
    }/*from   w  w  w. j  a v a 2  s.com*/

    private static String formatRelativeTime(String fullRelativeDate) {

        //Log.d("Debug", "Compose tweet time: " + fullRelativeDate);

        final String relativeDateFormat1 = "(\\d+)\\s(\\w+)\\s\\w+"; // "49 seconds ago"
        final Pattern relativeDatePattern1 = Pattern
                .compile(relativeDateFormat1);
        final String relativeDateFormat2 = "(\\w+)\\s(\\d+)\\s(\\w+)"; // "in 4 seconds"
        final Pattern relativeDatePattern2 = Pattern
                .compile(relativeDateFormat2);

        final Matcher matcher1 = relativeDatePattern1
                .matcher(fullRelativeDate);
        final Matcher matcher2 = relativeDatePattern2
                .matcher(fullRelativeDate);
        final StringBuilder sb = new StringBuilder();

        if (matcher1.matches()) {
            return sb.append(matcher1.group(1))
                    .append(matcher1.group(2).charAt(0)).toString();
        } else if (matcher2.matches()) {
            return sb.append(matcher2.group(2))
                    .append(matcher2.group(3).charAt(0)).toString();
        }

        // If the regex couldn't be parsed, make the relative timestamp manually
        // Should never happen though
        Log.d("debug", "Relative date didn't match pattern: "
                + fullRelativeDate);
        final String[] info = fullRelativeDate.split("\\s");
        if (info.length > 2) {
            sb.append(info[0].toString()).append(" ")
                    .append(info[1].toString().substring(0, 1));
        } else {
            sb.append(info[0].toString());
        }
        return sb.toString();
    }
}

Related

  1. getNameForFile(long time)
  2. getNumberOfDaysPassed(long date1, long date2)
  3. getReadableTimeStamp(long timeStamp)
  4. getReadableTimeUsage(long timeUsageMs)
  5. getRelativeDateLabel(long time)
  6. getShortDateString(long date, Locale locale)
  7. getShortDateTimeString(long date, Locale locale)
  8. getSimpleDatetime(long milliseconds)
  9. getStandardTime(long timestamp)