我正在尝试将日期转换为timeago。返回的内容:1小时前,1个月,2个月前,1年。

这是一个从WordPress获取博客帖子的Android应用。

但是,我当前的代码在48年前返回(针对每个帖子)。

我试图在互联网上找到答案,是的,那里的大多数答案都对我有所帮助,但我仍然在48年前的每一篇文章中都找到了答案。

那里的大多数答案都对我不起作用。

请注意,我没有使用Java8。很多答案都建议使用Java 8,但是我不能使用它。

public String parseDateToddMMyyyy(String time) {
    String inputPattern = "yyyy-MM-dd'T'HH:mm:ss";
    String outputPattern = "yyyy-MM-dd HH:mm:ss'Z'";
    SimpleDateFormat inputFormat = new SimpleDateFormat(inputPattern);
    SimpleDateFormat outputFormat = new SimpleDateFormat(outputPattern);

    inputFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    outputFormat.setTimeZone(TimeZone.getTimeZone("GMT"));

    Date date = null;
    String str = null;

    try {
        date = inputFormat.parse(time);
        str = outputFormat.format(date);

        long dateInMillinSecond = date.getTime();

        str = toDuration(dateInMillinSecond);

        Log.e("Blog - ", "Date " + date);
        //output for the dare is Sat May 19 22:59:42 EDT 2018

        Log.e("Blog - ", "Str " + str);
        //output is 48 years ago

    } catch (ParseException e) {
        e.printStackTrace();
    }
    return str;
}


我还发现了这两种将毫秒转换为时间的方法,并且我认为这两种方法都能找到。因此,我认为问题在于日期。日期格式未转换为毫秒(不确定)。

public static final List<Long> times = Arrays.asList(
    TimeUnit.DAYS.toMillis(365),
    TimeUnit.DAYS.toMillis(30),
    TimeUnit.DAYS.toMillis(1),
    TimeUnit.HOURS.toMillis(1),
    TimeUnit.MINUTES.toMillis(1),
    TimeUnit.SECONDS.toMillis(1));

public static final List<String> timesString =
    Arrays.asList("year","month","day","hour","minute","second");

public static String toDuration(long duration) {
    StringBuffer res = new StringBuffer();
    for(int i=0;i< times.size(); i++) {
        Long current = times.get(i);
        long temp = duration/current;
        if(temp>0) {
            res.append(temp).append(" ").append(timesString.get(i))
            .append(temp != 1 ? "s" : "").append(" ago");
            break;
        }
    }
    if("".equals(res.toString()))
        return "0 seconds ago";
    else
        return res.toString();
}


编辑

变量long dateInMilliSecond返回1524430807000

最佳答案

我将看一下您的代码,但我绝对应该这样说,48 years ago提醒我1970年1月1日。可能您向人性化功能发送了null或0作为日期。

审核后编辑:

我认为问题在于,您正在计算日期的持续时间,而不是差异。如果要计算真实的date ago,则应将时差发送到toDuration函数。

当前行为非常正常,因为您向x-x-2018函数发送了toDuration日期,并且基本上返回了48 years ago(因为零是1970)。您应该寄出差额。
例如;

long difference = System.currentTimeMillis() - dateInMillisecond;
String humanizedDate = toDuration(difference);

10-05 20:20
查看更多