Android SDK中的[DateUtils.getRelativeTimeSpanString()] [1]非常适合显示过去的相对时间。
即:5天前或5分钟前。
但是对于未来的日期似乎并不那么好。它似乎只打印日期。
是否有任何简单的替代方法可以为将来的日期生成相对时间跨度字符串(没有通过比较两个日历对象来写出能够计算出日,小时,分钟,秒的内容)?
长达5天或5分钟的线路?
这基本上是我必须做的,它看起来有点脏(注意:这段代码只是为帖子编写而不是实际上通过java编译器运行):
Calendar calendarIO = Calendar.getInstance();
calendarIO.set(2013, 2, 14, 7, 0);
long milliseconds1 = calendarIO.getTimeInMillis();
long milliseconds2 = System.currentTimeMillis();
long diff = milliseconds1 - milliseconds2;
long diffSeconds = diff / 1000;
long diffMinutes = diff / (60 * 1000);
long diffHours = diff / (60 * 60 * 1000);
long diffDays = diff / (24 * 60 * 60 * 1000);
String relativeTime = "";
if (diffDays > 1) {
relativeTime = diffDays + " days";
} else if (diffDays > 0) {
relativeTime = diffDays + " days " + diffHours + " hours";
} else if (diffHours > 1) {
relativeTime = diffHours + " hours";
} else if (diffMinutes > 0) {
relativeTime = diffMinutes + " minutes.";
}
答案 0 :(得分:5)
我尝试使用DateUtils.getRelativeTimeSpanString(time, now, minResolution)
,因为它适用于未来日期,使用“n天”格式。
http://developer.android.com/reference/android/text/format/DateUtils.html#getRelativeTimeSpanString
答案 1 :(得分:1)
遵循以下步骤
String dateString = "06/05/2019 06:49:00 AM";
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss aa");
Date convertedDate = new Date();
try {
convertedDate = dateFormat.parse(dateString);
long cuMillis = System.currentTimeMillis();
String timeAgo = (String) DateUtils.getRelativeTimeSpanString(convertedDate.getTime(), cuMillis, 1, FORMAT_ABBREV_RELATIVE);
Log.d("LOG", "Time Ago==>" + timeAgo);
} catch (ParseException e) {
e.printStackTrace();
}
答案 2 :(得分:0)
DateUtils.getRelativeTimeSpanString(endDate.getTime(), startDate.getTime(), DateUtils.FORMAT_ABBREV_RELATIVE);
以下警告:
明天而不是1天。