-2

我有一个 int 数,我需要将其转换为日期,但采用这种形式

("几秒前","几分钟前","几个小时前""昨天","几天前","上周","上个月","去年")

我可以得到日期

        int seconds =1320105600;

        int  millis = seconds * 1000;
        Date date = new Date(millis);
        SimpleDateFormat sdf = new SimpleDateFormat("EEEE,MMMM d,yyyy h:mm,a", Locale.ENGLISH);
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        String formattedDate = sdf.format(date);

我怎样才能把它转换成那种形式

4

2 回答 2

1

您应该创建一个函数来执行此操作:

int currentSeconds = ((int) System.currentTimeMillis())/ 1000;
int diff = currentSeconds - seconds;
if (diff < 60)
    formatedDate = "Few seconds ago";
else if (diff < 60 * 60)
    formatedDate = "Few minutes ago";

等等。

于 2013-10-30T09:43:54.597 回答
0

您可以使用Joda Time轻松获取两个日期之间的天数、分钟数和秒数差异。

java.util.Date d1, d2;

DateTime dt1 = new DateTime(d1);
DateTime dt2 = new DateTime(d2);

int numDays = Days.daysBetween(dt1, dt2).getDays(); 
int hours = Hours.hoursBetween(dt1, dt2).getHours() % 24;
int minutes = Minutes.minutesBetween(dt1, dt2).getMinutes() % 60);
int seconds = Seconds.secondsBetween(dt1, dt2).getSeconds() % 60);

if (numDays > 0) { return "A few days ago"; }
else if (hours > 0) { return "A few hours ago"; }
// And so on

您应该能够不费吹灰之力地适应这种模式以满足您的特定要求(有Years.yearsBetweeenMonths.monthsBetween方法)。

于 2013-10-30T09:44:23.850 回答