[英]Best way to compare two dates in Java (day criteria)?
I would like to know the best way to compare two Dates in Java , such as in this following scenario: 我想知道比较Java中两个Date的最佳方法,例如在以下情况下:
Date date = new Date(time);
Date now = new Date();
//
long day = 86400000L;
long days = day * 7;
if ((date.getTime() + days) <= now.getTime()) {
// DO 1
} else {
// DO 2
}
In other words: I would like to get a Date object, add in some days and compare them. 换句话说:我想获得一个Date对象,几天后添加并进行比较。
Question: Is there a good solution for Java 6? 问题: Java 6是否有好的解决方案? And for Java 8 (using the new Time API)?
对于Java 8(使用新的Time API)? I would like to use the Date.after(Date date) and Date.before(Date date) for this (after adding the days to a Date)
我想为此使用Date.after(Date date)和Date.before(Date date)(在将日期添加到Date之后)
Thank you! 谢谢!
EDIT 编辑
Looks like this can be done, according to Coffee. 根据Coffee的说法,看起来这可以做到。 I dont know if there's a better way.
我不知道是否有更好的方法。
Calendar date = Calendar.getInstance();
date.setTime(new Date(time));
date.add(Calendar.DATE, 7);
Calendar now = Calendar.getInstance();
//
if(now.after(date)) {
// DO 1
} else {
// DO 2
}
In Java 8: 在Java 8中:
LocalDate date = LocalDate.ofEpochDay(time); // days!
if (date.plusDays(7).isBefore(LocalDate.now())) {
// DO 1
} else {
// DO 2
}
EDIT
编辑
If time is in millis: 如果时间以毫秒为单位:
Date d = new Date();
d.setTime(time);
LocalDate date = d.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.