Skip to content Skip to sidebar Skip to footer

How To Convert Time To " Time Ago " In Android

My server. It return time : '2016-01-24T16:00:00.000Z' I want 1 : convert to String. 2 : I want it show ' time ago ' when load it from server. Please. Help me!

Solution 1:

I see mainly three ways:

a) built-in options using SimpleDateFormat and DateUtils

SimpleDateFormatsdf=newSimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
  sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
  try {
         longtime= sdf.parse("2016-01-24T16:00:00.000Z").getTime();
         longnow= System.currentTimeMillis();
         CharSequenceago=
                    DateUtils.getRelativeTimeSpanString(time, now, DateUtils.MINUTE_IN_MILLIS);
        } catch (ParseException e) {
            e.printStackTrace();
        }

b) external library ocpsoft/PrettyTime (based on java.util.Date)

Here you have to use SimpleDateFormat, too, to produce the time-result as interpretation of "2016-01-24T16:00:00.000Z".

import below lib in your app

implementation 'org.ocpsoft.prettytime:prettytime:4.0.1.Final'

PrettyTimeprettyTime=newPrettyTime(Locale.getDefault());
Stringago= prettyTime.format(newDate(time));

c) using my library Time4A (heavyweight but with best i18n-support)

Momentmoment= Iso8601Format.EXTENDED_DATE_TIME_OFFSET.parse("2016-01-24T16:00:00.000Z");
Stringago= PrettyTime.of(Locale.getDefault()).printRelativeInStdTimezone(moment);

Solution 2:

1 - create date formatter:

publicstaticfinalSimpleDateFormatinputFormat=newSimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

2 - create Date object

String dateStr = "2016-01-24T16:00:00.000Z";
Datedate = inputFormat.parse(dateStr);

3 - Use Android DateUtils to create a nice Display string:

String niceDateStr = DateUtils.getRelativeTimeSpanString(date.getTime() , Calendar.getInstance().getTimeInMillis(), DateUtils.MINUTE_IN_MILLIS);

Solution 3:

It's very simple. I'll tell you with my code.

package com.example;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

publicclassTimeShow
{
    publicstaticvoidmain(String[] args) {
        try 
        {
            SimpleDateFormatformat=newSimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss");
            Datepast= format.parse("2016.02.05 AD at 23:59:30");
            Datenow=newDate();
            long seconds=TimeUnit.MILLISECONDS.toSeconds(now.getTime() - past.getTime());
            long minutes=TimeUnit.MILLISECONDS.toMinutes(now.getTime() - past.getTime());
            long hours=TimeUnit.MILLISECONDS.toHours(now.getTime() - past.getTime());
            long days=TimeUnit.MILLISECONDS.toDays(now.getTime() - past.getTime());
////          System.out.println(TimeUnit.MILLISECONDS.toSeconds(now.getTime() - past.getTime()) + " milliseconds ago");//          System.out.println(TimeUnit.MILLISECONDS.toMinutes(now.getTime() - past.getTime()) + " minutes ago");//          System.out.println(TimeUnit.MILLISECONDS.toHours(now.getTime() - past.getTime()) + " hours ago");//          System.out.println(TimeUnit.MILLISECONDS.toDays(now.getTime() - past.getTime()) + " days ago");if(seconds<60)
            {
                System.out.println(seconds+" seconds ago");
            }
            elseif(minutes<60)
            {
                System.out.println(minutes+" minutes ago");
            }
            elseif(hours<24)
            {
                System.out.println(hours+" hours ago");
            }
            else 
            {
                System.out.println(days+" days ago");
            }
        }
        catch (Exception j){
            j.printStackTrace();
        }
    }
}

Solution 4:

using @Excelso_Widi code, i was able to overcome,

I modified his code and also translated to English.

publicclassTimeAgo2 {

    public String covertTimeToText(String dataDate) {

        StringconvTime=null;

        Stringprefix="";
        Stringsuffix="Ago";

        try {
            SimpleDateFormatdateFormat=newSimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
            DatepasTime= dateFormat.parse(dataDate);

            DatenowTime=newDate();

            longdateDiff= nowTime.getTime() - pasTime.getTime();

            longsecond= TimeUnit.MILLISECONDS.toSeconds(dateDiff);
            longminute= TimeUnit.MILLISECONDS.toMinutes(dateDiff);
            longhour= TimeUnit.MILLISECONDS.toHours(dateDiff);
            longday= TimeUnit.MILLISECONDS.toDays(dateDiff);

            if (second < 60) {
                convTime = second + " Seconds " + suffix;
            } elseif (minute < 60) {
                convTime = minute + " Minutes "+suffix;
            } elseif (hour < 24) {
                convTime = hour + " Hours "+suffix;
            } elseif (day >= 7) {
                if (day > 360) {
                    convTime = (day / 360) + " Years " + suffix;
                } elseif (day > 30) {
                    convTime = (day / 30) + " Months " + suffix;
                } else {
                    convTime = (day / 7) + " Week " + suffix;
                }
            } elseif (day < 7) {
                convTime = day+" Days "+suffix;
            }

        } catch (ParseException e) {
            e.printStackTrace();
            Log.e("ConvTimeE", e.getMessage());
        }

        return convTime;
    }

}

and i used it like this

Stringtime= jsonObject.getString("date_gmt");
 TimeAgo2timeAgo2=newTimeAgo2();
StringMyFinalValue= timeAgo2.covertTimeToText(time);

Happy coding and thanks @Excelso_Widi you the man wink

Solution 5:

In Android you can use DateUtils.getRelativeTimeSpanString(long timeInMillis), referring to https://developer.android.com/reference/android/text/format/DateUtils.html you can use one of the variations of that method for accuracy.

Post a Comment for "How To Convert Time To " Time Ago " In Android"