定制 Android 日期,让它像 Twitter 和 Instagram 的新闻源一样。

5

如何在Android开发中自定义日期格式,使其类似于Twitter和Instagram。下面是我当前的代码,但我不喜欢它产生的格式,例如“11分钟前”或“34分钟前”。我更喜欢Twitter的格式,例如“11m”或“34m”。请问有人知道我如何将我的日期格式化为这样吗?

Date createdAt = message.getCreatedAt();//get the date the message was created from parse backend
        long now = new Date().getTime();//get current date
        String convertedDate = DateUtils.getRelativeTimeSpanString(
                createdAt.getTime(), now, DateUtils.SECOND_IN_MILLIS).toString();
        mPostMessageTimeLabel.setText(convertedDate); //sets the converted date into the message_item.xml view
2个回答

7

我曾经遇到过同样的问题。不过我没有使用库,我想我可以自己写一个版本,这样更容易理解正在发生的事情(如果需要的话还可以进行微调)。

下面是我制作的实用方法(包括有用的Log语句,供Android用户测试):

public static String convertLongDateToAgoString (Long createdDate, Long timeNow){
        Long timeElapsed = timeNow - createdDate;

        // For logging in Android for testing purposes
        /*
        Date dateCreatedFriendly = new Date(createdDate);
        Log.d("MicroR", "dateCreatedFriendly: " + dateCreatedFriendly.toString());
        Log.d("MicroR", "timeNow: " + timeNow.toString());
        Log.d("MicroR", "timeElapsed: " + timeElapsed.toString());*/

        // Lengths of respective time durations in Long format.
        Long oneMin = 60000L;
        Long oneHour = 3600000L;
        Long oneDay = 86400000L;
        Long oneWeek = 604800000L;

        String finalString = "0sec";
        String unit;

        if (timeElapsed < oneMin){
            // Convert milliseconds to seconds.
            double seconds = (double) ((timeElapsed / 1000));
            // Round up
            seconds = Math.round(seconds);
            // Generate the friendly unit of the ago time
            if (seconds == 1) {
                unit = "sec";
            } else {
                unit = "secs";
            }
            finalString = String.format("%.0f", seconds) + unit;
        } else if (timeElapsed < oneHour) {
            double minutes = (double) ((timeElapsed / 1000) / 60);
            minutes = Math.round(minutes);
            if (minutes == 1) {
                unit = "min";
            } else {
                unit = "mins";
            }
            finalString = String.format("%.0f", minutes) + unit;
        } else if (timeElapsed < oneDay) {
            double hours   = (double) ((timeElapsed / 1000) / 60 / 60);
            hours = Math.round(hours);
            if (hours == 1) {
                unit = "hr";
            } else {
                unit = "hrs";
            }
            finalString = String.format("%.0f", hours) + unit;
        } else if (timeElapsed < oneWeek) {
            double days   = (double) ((timeElapsed / 1000) / 60 / 60 / 24);
            days = Math.round(days);
            if (days == 1) {
                unit = "day";
            } else {
                unit = "days";
            }
            finalString = String.format("%.0f", days) + unit;
        } else if (timeElapsed > oneWeek) {
            double weeks = (double) ((timeElapsed / 1000) / 60 / 60 / 24 / 7);
            weeks = Math.round(weeks);
            if (weeks == 1) {
                unit = "week";
            } else {
                unit = "weeks";
            }
            finalString = String.format("%.0f", weeks) + unit;
        }
        return finalString;
    }

使用方法:

Long createdDate = 1453394736888L; // Your Long
Long timeNow = new Date().getTime();
Log.d("MicroR", convertLongDateToAgoString(createdDate, timeNow));

// Outputs:
// 1min
// 3weeks
// 5hrs
// etc.

欢迎随时测试此功能,如果您发现任何问题,请告诉我!


正是我所需要的。谢谢! - olajide
多么棒的代码! - Bipin Bharti
如果timeElapsed恰好为1周,则它不起作用。我认为我们可以删除if(timeElapsed> oneWeek),因为在这种情况下它实际上总是超过一周。 - sembozdemir

1
我可能有些晚了,但我会写下来给那些正在寻找解决方案的人。 使用PrettyTime可以获取格式化日期,例如“2个月前”等等。 为适应您的需求,您需要提供一个自定义的TimeFormat对象,无需创建新的TimeUnit对象,因为我们正在格式化普通的时间单位。 要做到这一点,只需为分钟创建您的TimeFormat对象:
public class CustomMinuteTimeFormat implements TimeFormat {
@Override
public String format(Duration duration) {
    return Math.abs(duration.getQuantity()) + "m";
}

@Override
public String formatUnrounded(Duration duration) {
    return format(duration);
}

@Override
public String decorate(Duration duration, String time) {
    return time;
}

@Override
public String decorateUnrounded(Duration duration, String time) {
    return time;
}
}

然后实例化一个新的PrettyTime实例并设置格式化程序。
PrettyTime pretty = new PrettyTime();
//This line of code is very important
pretty.registerUnit(new Minute(), new CustomMinuteTimeFormat());
//Use your PrettyTime object as usual
pretty.format(yourDateObject);

如果经过的时间是2分钟,那么这将输出“2m”。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接