android记录下根据十位时间戳实现,几分钟前,几小时前,几天前

127 阅读1分钟
    public static String getRelativeTime(long timestamp) {       
        long timeInMillis = timestamp * 1000;     
        long currentTime = System.currentTimeMillis();     
        long timeDifference = currentTime - timeInMillis;       
        if (timeDifference < TimeUnit.MINUTES.toMillis(1)) {
            return "just now";
        } else if (timeDifference < TimeUnit.HOURS.toMillis(1)) {
            long minutes = TimeUnit.MILLISECONDS.toMinutes(timeDifference);
            return minutes + " minute" + (minutes > 1 ? "s" : "") + " ago";
        } else if (timeDifference < TimeUnit.DAYS.toMillis(1)) {
            long hours = TimeUnit.MILLISECONDS.toHours(timeDifference);
            return hours + " hour" + (hours > 1 ? "s" : "") + " ago";
        } else if (timeDifference < TimeUnit.DAYS.toMillis(365)) {
            long days = TimeUnit.MILLISECONDS.toDays(timeDifference);
            return days + " day" + (days > 1 ? "s" : "") + " ago";
        } else {
            long years = TimeUnit.MILLISECONDS.toDays(timeDifference) / 365;
            return years + " year" + (years > 1 ? "s" : "") + " ago";
        }
    }