java.util.Date
其中没有时区,因此解析和格式化订单日期没有意义。格式化将其转换为 aString
并解析将其转换回 a Date
,这是没有意义的,因为订单日期已经是一个Date
对象。
您必须在第一个格式化程序(变量)中设置时区,然后format
解析from和to日期:它们将被设置为加尔各答时区的相应日期和时间 - 在这种情况下它是有效的,因为您有字符串并且想要将它们转换为日期。
然后,您使用额外的括号进行比较以避免任何歧义(如评论中所指出的)。Date
并且将其设置为 a是没有意义的Calendar
,只是为了稍后将其取回 - 该Calendar
实例在您的代码中没有任何用途。
并且调用getOrderDate
不应该在for
循环内?
完整的代码将是这样的:
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
// from and to dates are from Kolkata's timezone, so the formatter must know that
format.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
// dates will be equivalent to this date and time in Kolkata, although
// the date itself doesn't store the timezone in it
Date fromDate = format.parse(from + " 00:00:00");
Date toDate = format.parse(to + " 23:59:59");
for(Order order : orders){
Date orderDate = order.getOrderDate();
// note the extra parenthesis, they make all the difference
if( (orderDate.after(fromDate) || orderDate.equals(fromDate)) &&
(orderDate.before(toDate) || orderDate.equals(toDate)) ) {
....
}
}
如果您的 Java >= 8,最好使用java.time
API:
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd-MM-yyyy");
ZoneId zone = ZoneId.of("Asia/Kolkata");
ZonedDateTime fromDate = LocalDate
// parse "from" string
.parse(from, fmt)
// start of day at Kolkata timezone
.atStartOfDay(zone);
ZonedDateTime toDate = LocalDate
// parse "to" string
.parse(to, fmt)
// get start of next day
.plusDays(1).atStartOfDay(zone);
// convert the Date to ZonedDateTime
for (Order order : orders) {
ZonedDateTime orderDate = order.getOrderDate().toInstant().atZone(zone);
if ((orderDate.isAfter(fromDate) || orderDate.isEqual(fromDate)) && (orderDate.isBefore(toDate))) {
...
}
}
这是一个不同的代码,因为这个 API 引入了新的类型和概念,但它比以前的 API 有了很大的改进(Date
并且Calendar
是混乱的、有缺陷的和过时的)。
花一些时间研究这个 API,这是完全值得的:https ://docs.oracle.com/javase/tutorial/datetime/