像Twitter一样显示时间

时间:2017-01-06 11:06:50

标签: java android time java-time

我正在使用DateUtils.getRelativeTimeSpanString()来显示帖子。

它返回的字符串是这样的: 1分钟前,但我希望 1 m 1 h 等等在(缩短和没有)之前。

我可以将“小时”替换为“h”或“分钟”替换为“m”,但如果语言与英语不同则无效。这是Twitter正在使用的内容。 英语/西里尔语通过Twitter显示的方式。

enter image description here

enter image description here

更新:我会接受@Bradley Wilson的回答,虽然我会在这里添加更清晰的解决方案(再次使用JodaTime包)。其余的答案也可以修改为相同的结果,所以他们值得投票。谢谢大家:

    DateTime postMaded = new DateTime(your previous date);
    DateTime nowUpdate = new DateTime();

    Period period = new Period(postMaded, nowUpdate);

    PeriodFormatter formatter;

    Locale current = ConverterMethods.getCurrentLocale();

    if (current.getLanguage().contentEquals(any Cyrillic language )) {

        if (period.getYears() != 0) {
            formatter = new PeriodFormatterBuilder().appendYears().appendSuffix(" г.").printZeroNever().toFormatter();
        } else if (period.getMonths() != 0) {
            formatter = new PeriodFormatterBuilder().appendMonths().appendSuffix(" м").printZeroNever().toFormatter();
        } else if (period.getWeeks() != 0) {
            formatter = new PeriodFormatterBuilder().appendWeeks().appendSuffix(" седм.").printZeroNever().toFormatter();
        } else if (period.getDays() != 0) {
            formatter = new PeriodFormatterBuilder().appendDays().appendSuffix(" д").printZeroNever().toFormatter();
        } else if (period.getHours() != 0) {
            formatter = new PeriodFormatterBuilder().appendHours().appendSuffix(" ч").printZeroNever().toFormatter();
        } else if (period.getMinutes() != 0) {
            formatter = new PeriodFormatterBuilder().appendMinutes().appendSuffix(" мин").printZeroNever().toFormatter();
        } else {
            formatter = new PeriodFormatterBuilder().appendSeconds().appendSuffix(" с").printZeroNever().toFormatter();
        }

    } else {

        if (period.getYears() != 0) {
            formatter = new PeriodFormatterBuilder().appendYears().appendSuffix(" y").printZeroNever().toFormatter();
        } else if (period.getMonths() != 0) {
            formatter = new PeriodFormatterBuilder().appendMonths().appendSuffix(" mon").printZeroNever().toFormatter();
        } else if (period.getWeeks() != 0) {
            formatter = new PeriodFormatterBuilder().appendWeeks().appendSuffix(" w").printZeroNever().toFormatter();
        } else if (period.getDays() != 0) {
            formatter = new PeriodFormatterBuilder().appendDays().appendSuffix(" d").printZeroNever().toFormatter();
        } else if (period.getHours() != 0) {
            formatter = new PeriodFormatterBuilder().appendHours().appendSuffix(" h").printZeroNever().toFormatter();
        } else if (period.getMinutes() != 0) {
            formatter = new PeriodFormatterBuilder().appendMinutes().appendSuffix(" m").printZeroNever().toFormatter();
        } else {
            formatter = new PeriodFormatterBuilder().appendSeconds().appendSuffix(" s").printZeroNever().toFormatter();
        }
    }

4 个答案:

答案 0 :(得分:4)

查看PrettyTime库。

使用起来非常简单:

import org.ocpsoft.prettytime.PrettyTime

PrettyTime p = new PrettyTime();
System.out.println(p.format(new Date()));
// prints "moments ago"

您还可以传入国际化消息的区域设置:

PrettyTime p = new PrettyTime(new Locale("fr"));
System.out.println(p.format(new Date()));
// prints "à l'instant"

如评论中所述,Android在android.text.format.DateUtils类中内置了此功能。

答案 1 :(得分:2)

您可以使用此功能执行此操作

  public static String getTimeAgo(long time) {
     if (time < 1000000000000L) {
     // if timestamp given in seconds, convert to millis
     time *= 1000;
  }

  long now = System.currentTimeMillis();
  if (time > now || time <= 0) {
     return null;
  }

  // TODO: localize
  final long diff = now - time;
  if (diff < MINUTE_MILLIS) {
     return "just now";
  } else if (diff < 2 * MINUTE_MILLIS) {
     return "a minute ago";
  } else if (diff < 50 * MINUTE_MILLIS) {
     return diff / MINUTE_MILLIS + " min ago";
  } else if (diff < 90 * MINUTE_MILLIS) {
     return "an hour ago";
  } else if (diff < 24 * HOUR_MILLIS) {
     return diff / HOUR_MILLIS + " hours ago";
  } else if (diff < 48 * HOUR_MILLIS) {
     return "yesterday";
  } else {
     return diff / DAY_MILLIS + " days ago";
  }
 }

答案 2 :(得分:1)

您可以使用JodaTime来实现此目标:

将依赖项添加到您的应用级Build.Gradle文件中,如下所示:

compile 'net.danlew:android.joda:2.9.4.1'

然后你可以简单地实现这个功能。

private String time = "Just Now";

private String how_long_ago(String created_at) {
        DateTime sinceGraduation = new DateTime(created_at, GregorianChronology.getInstance());
        DateTime currentDate = new DateTime(); //current date

        Months diffInMonths = Months.monthsBetween(sinceGraduation, currentDate);
        Days diffInDays = Days.daysBetween(sinceGraduation, currentDate);
        Hours diffInHours = Hours.hoursBetween(sinceGraduation, currentDate);
        Minutes diffInMinutes = Minutes.minutesBetween(sinceGraduation, currentDate);
        Seconds seconds = Seconds.secondsBetween(sinceGraduation, currentDate);

        Log.d("since grad", "before if " + sinceGraduation);
        if (diffInDays.isGreaterThan(Days.days(31))) {
            time = diffInMonths.getMonths() + " months ago";
            if (diffInMonths.getMonths() == 1) {
                time = diffInMonths.getMonths() + " month ago";
            } else {
                time = diffInMonths.getMonths() + " months ago";
            }
            return time;
        } else if (diffInHours.isGreaterThan(Hours.hours(24))) {
            if (diffInDays.getDays() == 1) {
                time = diffInDays.getDays() + " day ago";
            } else {
                time = diffInDays.getDays() + " days ago";
            }
            return time;
        } else if (diffInMinutes.isGreaterThan(Minutes.minutes(60))) {
            if (diffInHours.getHours() == 1) {
                time = diffInHours.getHours() + " hour ago";
            } else {
                time = diffInHours.getHours() + " hours ago";
            }
            return time;
        } else if (seconds.isGreaterThan(Seconds.seconds(60))) {
            if (diffInMinutes.getMinutes() == 1) {
                time = diffInMinutes.getMinutes() + " minute ago";
            } else {
                time = diffInMinutes.getMinutes() + " minutes ago";
            }
            return time;
        } else if (seconds.isLessThan(Seconds.seconds(60))) {
            return time;
        }
        Log.d("since grad", "" + sinceGraduation);
        return time;
    }

只需更改String的{​​{1}}输出即可达到所需的'1m'

注意:您可以使用本地化通过资源更改字符串。

有关详细信息,请参阅Android Localization Tutorial

答案 3 :(得分:1)

使用我的库Time4A可以像您在问题中指定的那样工作:

打印相对时间(使用以前的字词)

    PlainTimestamp now = PlainTimestamp.nowInSystemTime();
    PlainTimestamp earlier = now.minus(1, ClockUnit.MINUTES);
    Moment past = earlier.inStdTimezone();
    Locale russian = new Locale("ru");

    PrettyTime.of(Locale.ENGLISH).printRelativeInStdTimezone(past);
    // output: 1 minute ago

    PrettyTime.of(Locale.ENGLISH)
       .withShortStyle().printRelativeInStdTimezone(past);
    // output: 1 min. ago

    PrettyTime.of(russian).printRelativeInStdTimezone(past);
    // output: 1 минуту назад

    PrettyTime.of(russian).withShortStyle().printRelativeInStdTimezone(past);
    // output: 1 мин. назад

在没有前一词的情况下打印平时

    IsoUnit days = CalendarUnit.DAYS;
    IsoUnit hours = ClockUnit.HOURS;
    IsoUnit minutes = ClockUnit.MINUTES;
    net.time4j.Duration<IsoUnit> d =
        Duration.in(Timezone.ofSystem(), days, hours, minutes)
            .between(earlier, now);

    PrettyTime.of(Locale.ENGLISH).print(d, TextWidth.WIDE);
    // output: 1 minute

    PrettyTime.of(Locale.ENGLISH).print(d, TextWidth.ABBREVIATED);
    // output: 1 min

    PrettyTime.of(Locale.ENGLISH).print(d, TextWidth.NARROW);
    // output: 1m

    PrettyTime.of(russian).print(d, TextWidth.WIDE);
    // output: 1 минута

    PrettyTime.of(russian).print(d, TextWidth.ABBREVIATED);
    // output: 1 мин

    PrettyTime.of(russian).print(d, TextWidth.NARROW);
    // output: 1 мин

最新的库版本使用CLDR-repository v30.0.2的数据(来自Unicode-consortium,实际上是80种语言)。如有必要,您可能希望通过定义自己的资产来与Time4A一起分发(然后覆盖默认资产)来更改文本资源。