目前我有一个Date记录的实例,如下所示:
Calendar recordDate = Calendar.getInstance();
try {
recordDate .setTime(sdf.parse(joinPlanDate));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
问题是,通常我可以显示日期,如2014-08-20 15:05:11等......我想使用其他格式,例如
今天,昨天,几天前,一周前,几周前,一年前,几年前等。
是否有android格式化程序已经可以处理这种情况或者如何创建格式化程序?谢谢你的帮助
答案 0 :(得分:2)
创建了一个函数,它给了我像twitter这样的字符串让一个花药回答看到它并从中获取想法并定制自己的方式:)
public static String getTimeString(Date fromdate) {
SimpleDateFormat twtimeformat = new SimpleDateFormat(
"dd MMM");
long then;
then = fromdate.getTime();
Date date = new Date(then);
StringBuffer dateStr = new StringBuffer();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
Calendar now = Calendar.getInstance();
int days = daysBetween(calendar.getTime(), now.getTime());
int minutes = hoursBetween(calendar.getTime(), now.getTime());
int hours = minutes / 60;
if (days == 0) {
int second = minuteBetween(calendar.getTime(), now.getTime());
if (minutes > 60) {
if (hours >= 1 && hours <= 24) {
dateStr.append(hours).append("h");
}
} else {
if (second <= 10) {
dateStr.append("Now");
} else if (second > 10 && second <= 30) {
dateStr.append("few seconds ago");
} else if (second > 30 && second <= 60) {
dateStr.append(second).append("s");
} else if (second >= 60 && minutes <= 60) {
dateStr.append(minutes).append("m");
}
}
} else
if (hours > 24 && days <= 7) {
dateStr.append(days).append("d");
} else {
dateStr.append(twtimeformat.format(date));
}
return dateStr.toString();
}
public static int minuteBetween(Date d1, Date d2) {
return (int) ((d2.getTime() - d1.getTime()) / DateUtils.SECOND_IN_MILLIS);
}
public static int hoursBetween(Date d1, Date d2) {
return (int) ((d2.getTime() - d1.getTime()) / DateUtils.MINUTE_IN_MILLIS);
}
public static int daysBetween(Date d1, Date d2) {
return (int) ((d2.getTime() - d1.getTime()) / DateUtils.DAY_IN_MILLIS);
}
答案 1 :(得分:1)
请参阅此DateUtil方法
如果你想要的话,这是标准的内置方法,而不是你自己定制的
String relativeString = getRelativeDateTimeString (this, System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS,DateUtils.WEEK_IN_MILLIS, 0));