Android/java 之前的一段时间 [已关闭]

2022-09-02 00:20:01

我是Java和Android的新手。我的一个Android新闻应用程序,我将时间显示为“7 August 2014,8:20 am”

但我需要像这样显示它:

5 mins ago    
1 hour ago    
2 days ago

发现很多图书馆,比如我们漂亮的时间,joda。但我不知道如何将其添加到我的Android应用程序中。甚至这个链接 https://stackoverflow.com/a/13018647/2020685 给我看。但是如何将我的日期和时间传递到其中。

任何简单的代码来做到这一点。

谢谢


答案 1

要显示的内容称为相对时间显示。Android 提供了显示相对于当前时间的时间的方法。您不必为此目的使用任何第三方库。

您可以使用

DateUtils.getRelativeTimeSpanString(long time, long now, long minResolution)

在此处参考文档

例如。

DateUtils.getRelativeTimeSpanString(your_time_in_milliseconds, current_ time_in_millisecinds,DateUtils.MINUTE_IN_MILLIS);

更新1:

您可以尝试通过以下方式传递日期并获取毫秒。

public static long getDateInMillis(String srcDate) {
    SimpleDateFormat desiredFormat = new SimpleDateFormat(
        "d MMMM yyyy, hh:mm aa");

    long dateInMillis = 0;
    try {
        Date date = desiredFormat.parse(srcDate);
        dateInMillis = date.getTime();
        return dateInMillis;
    } catch (ParseException e) {
        Log.d("Exception while parsing date. " + e.getMessage());
        e.printStackTrace();
    }

    return 0;
    }

希望它能帮助你。


答案 2

创建以下逻辑:

将您的时间转换为秒,从当前文件中获取差异( delta ):

  1. % it by 3600*365
    • 如果 则 显示年份 前result > 0
  2. else % it by 3600 * 30
    • 如果 则 显示月份前result > 0
  3. else % it by 3600 * 7
    • 如果 则 显示 周 前result > 0
  4. else % it by 3600
    • 如果 则 显示日前result > 0
  5. else % it by 3600 / 24
    • 如果 则 显示小时前result > 0
  6. else % it by 60,
    • 如果 则 显示 分钟 前result > 0

注:%表示模量(模数操作)


推荐