我需要帮助。我有两个约会。
private Date endDate;
private Date now;
public String getRemainingTime(endDate) {
now = new Date();
//logic
}
而且我还有一个方法可以在String formate中返回两个日期之间的差异,如果差异超过1天 - 例如“1天15分钟”;
如果差异超过1小时但不到1天 - 例如“1小时13分钟”;
如果差异小于1小时 - “35分39秒”,就像这样......
请帮帮我,我不熟悉java。
答案 0 :(得分:1)
如果建议的评论链接没有锻炼,那么试试这个: `
Date endDate;
Date now;
StringBuilder sb = new StringBuilder();
//timestamp difference in millis
Long diff = endaDate.getTime() - now.getTime();
//get the seconds
long seconds = diff / 1000;
//get the minutes
long minutes = diff / (1000 * 60);
//get the hours
long hrs = diff / (1000 * 60 * 60);
if (hrs > 0) {
sb.append(hrs + " hrs");
if (minutes % 60 > 0) {
sb.append(", " + minutes % 60 + " mins");
}
if (seconds % 60 > 0) {
sb.append(", " + seconds % 60 + " secs");
}
} else if (minutes % 60 > 0) {
sb.append(minutes % 60 + " mins");
if (seconds % 60 > 0) {
sb.append(", " + seconds % 60 + " secs");
}
} else if (seconds % 60 > 0) {
sb.append(seconds % 60 + " secs");
} else {
sb.append("00");
}
System.out.println(sb.toString());
`
答案 1 :(得分:1)
<强>更新强>
1)此代码将完成工作(编译器将包装常量):
public String getIntervalAsString(Date date1, Date date2) {
String format;
long dT = date2.getTime() - date1.getTime();
if (dT < 1000 * 60)
format = "s 'sec'";
else if (dT < 1000 * 60 * 60)
format = "m 'min' s 'sec'";
else if (dT < 1000 * 60 * 60 * 24)
format = "h 'hour(s)' m 'min'";
else if (dT < 1000 * 60 * 60 * 24 * 365)
format = "d 'day(s)' h 'hour(s)'";
else
format = "'more than a year'";
SimpleDateFormat formatter = new SimpleDateFormat(format);
return formatter.format(new Date(dT));
}
2)您可以尝试不同的模式here
答案 2 :(得分:1)
private static final long MILLIS_PER_SECOND = 1000L;
private static final long MILLIS_PER_MINUTE = MILLIS_PER_SECOND * 60L;
private static final long MILLIS_PER_HOUR = MILLIS_PER_MINUTE * 60L;
private static final long MILLIS_PER_DAY = MILLIS_PER_HOUR * 24L;
public String getRemainingTime(Date endDate) {
long remain = endDate.getTime() - System.currentTimeMillis();
if (remain <= 0L) {
return "pass";
}
long days = remain / MILLIS_PER_DAY;
long hours = (remain % MILLIS_PER_DAY) / MILLIS_PER_HOUR;
long minutes = (remain % MILLIS_PER_HOUR) / MILLIS_PER_MINUTE;
long seconds = (remain % MILLIS_PER_MINUTE) / MILLIS_PER_SECOND;
StringBuilder sb = new StringBuilder();
if (days > 0L) {
sb.append(days).append(" day ");
}
if (hours > 0L || days > 0L) {
sb.append(hours).append(" hour ");
}
if (minutes > 0L || days > 0L || hours > 0L) {
sb.append(minutes).append(" min ");
}
if (seconds > 0L) {
sb.append(seconds).append(" sec");
}
return sb.toString();
}
答案 3 :(得分:0)
Joda-Time库可能符合您的需求:
DateTime now
DateTime endDate;
Period p = new Period(now, endDate);
long hours = p.getHours();
long minutes = p.getMinutes();