如何将字符串时间戳更改为人类可读日期格式?

时间:2017-02-28 12:26:05

标签: java android

我试图将字符串时间戳转换为如下内容:

2分钟前。 1小时前。 4天前。 3个星期前。 5个月前。 1年前。

我使用Java的DateUtils.getRelativeTimeSpanString()方法进行转换,但它的显示日期与2016年1月1日相同。我希望它显示为6个月前。

以下是代码:

long now = System.currentTimeMillis();
System.err.println();

DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.ENGLISH);
Date startDate;

try {
    startDate = df.parse(userLogs.get(i).getDate());
    String sds = (String) DateUtils.getRelativeTimeSpanString(startDate.getTime(),System.currentTimeMillis(),DateUtils.MINUTE_IN_MILLIS);
    System.err.println(sds);
} catch (ParseException e) {
    e.printStackTrace();
}

更新:我不想使用Joda时间或任何其他库,为什么它被标记为重复我不明白!

1 个答案:

答案 0 :(得分:1)

请尝试使用此课程

 long time = Long.valueOf(getDateFromDateTime("2016-09-01 15:57:20"));//2016-09-01 15:57:20 pass your date here

    String timeStr = TimeUtility.timeAgo(time/1000);

输出:一分钟前

public long getDateFromDateTime(String date) {
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
            Locale.US);
    Date new_date;
    long t = 0L;
    try {
        new_date = df.parse(date);
        t = new_date.getTime();
        return t;
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return 0;
}


public class TimeUtility {

public static String timeAgo(long time_ago) {
    long cur_time = (Calendar.getInstance().getTimeInMillis()) / 1000;
    long time_elapsed = cur_time - time_ago;
    long seconds = time_elapsed;
    int minutes = Math.round(time_elapsed / 60);
    int hours = Math.round(time_elapsed / 3600);
    int days = Math.round(time_elapsed / 86400);
    int weeks = Math.round(time_elapsed / 604800);
    int months = Math.round(time_elapsed / 2600640);
    int years = Math.round(time_elapsed / 31207680);

    // Seconds
    if (seconds <= 60) {
        return "just now";
    }
    //Minutes
    else if (minutes <= 60) {
        if (minutes == 1) {
            return "one minute ago";
        } else {
            return minutes + " minutes ago";
        }
    }
    //Hours
    else if (hours <= 24) {
        if (hours == 1) {
            return "an hour ago";
        } else {
            return hours + " hrs ago";
        }
    }
    //Days
    else if (days <= 7) {
        if (days == 1) {
            return "yesterday";
        } else {
            return days + " days ago";
        }
    }
    //Weeks
    else if (weeks <= 4.3) {
        if (weeks == 1) {
            return "a week ago";
        } else {
            return weeks + " weeks ago";
        }
    }
    //Months
    else if (months <= 12) {
        if (months == 1) {
            return "a month ago";
        } else {
            return months + " months ago";
        }
    }
    //Years
    else {
        if (years == 1) {
            return "one year ago";
        } else {
            return years + " years ago";
        }
    }
}

}