我们怎样才能有时间?
例如:
1分钟前
1秒前
今天
昨天
星期二
在7天(1周前)之前必须显示日期。
答案 0 :(得分:1)
如果您保存日期,则可以使用期间:
DateTime myDate = new DateTime(1978, 3, 26, 12, 35, 0, 0);
DateTime now = new DateTime();
Period period = new Period(myDate, now);
PeriodFormatter formatter = new PeriodFormatterBuilder()
.appendSeconds().appendSuffix(" seconds ago\n")
.appendMinutes().appendSuffix(" minutes ago\n")
.appendHours().appendSuffix(" hours ago\n")
.appendDays().appendSuffix(" days ago\n")
.appendWeeks().appendSuffix(" weeks ago\n")
.appendMonths().appendSuffix(" months ago\n")
.appendYears().appendSuffix(" years ago\n")
.printZeroNever()
.toFormatter();
String elapsed = formatter.print(period);
System.out.println(elapsed);
打印:
3 seconds ago
51 minutes ago
7 hours ago
6 days ago
10 months ago
31 years ago
答案 1 :(得分:0)
我使用DateUtils.getRelativeTimeSpanString()完成了类似的事情。
一旦它>>它将在日期返回1周
public String timeSinceNow(Date date) {
long test = date.getTime();
String result = "";
long millis = System.currentTimeMillis();
long milliseconds = (millis - test);
long minutes = 0;
long hours = 0;
long days = 0;
days = (int) (milliseconds / (1000 * 60 * 60 * 24));
hours = (int) ((milliseconds - (1000 * 60 * 60 * 24 * days)) / (1000 * 60 * 60));
minutes = (int) (milliseconds - (1000 * 60 * 60 * 24 * days) - (1000 * 60 * 60 * hours)) / (1000 * 60);
if (days > 0 || hours > 0 || minutes > 0) {
if (hours > 0) {
if (minutes > 0) {
if (days == 0) {
if (hours == 0) {
if (minutes < 3) {
result = "Now";
} else {
result = (String) DateUtils.getRelativeTimeSpanString(test, System.currentTimeMillis(), 0);
}
} else {
result = (String) DateUtils.getRelativeTimeSpanString(test, System.currentTimeMillis(), 0);
}
}
else{
result = (String) DateUtils.getRelativeTimeSpanString(test, System.currentTimeMillis(), 0);
}
}else{
result = (String) DateUtils.getRelativeTimeSpanString(test, System.currentTimeMillis(), 0);
}
}else{
result = (String) DateUtils.getRelativeTimeSpanString(test, System.currentTimeMillis(), 0);
}
} else {
result = "Now";
}
return result;
}
这将返回一个String,其中“Now”与您作为参数传递的日期
之间存在差异