[英]java difference between two dates
我需要帮助。 我有两个约会。
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不熟悉。
如果建议的评论链接不起作用,请尝试以下方法:
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)该代码将完成这项工作(编译器将包装常量):
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)您可以在这里尝试不同的模式
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();
}
Joda-Time库可能符合您的需求:
DateTime now
DateTime endDate;
Period p = new Period(now, endDate);
long hours = p.getHours();
long minutes = p.getMinutes();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.