Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
931 views
in Technique[技术] by (71.8m points)

datetime - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I see mainly three ways:

a) built-in options using SimpleDateFormat and DateUtils

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
  sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
  try {
         long time = sdf.parse("2016-01-24T16:00:00.000Z").getTime();
         long now = System.currentTimeMillis();
         CharSequence ago =
                    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'

PrettyTime prettyTime = new PrettyTime(Locale.getDefault());
String ago = prettyTime.format(new Date(time));

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...