0

我需要从托管在在线服务器中的 Mongodb 数据中获取两个日期之间的数据。我尝试了这段代码,它在我的本地主机(本地数据和实时数据)中运行良好。但是当我在网上上传应用程序时,它在 Live 中无法正常工作。

结果在现场不准确。它在指定日期之前和之后获取一些记录。例如,我给出的日期是 01-02-2018 和 28-02-2018,结果将带有 31-01-2018 和 01-03-2018 的记录。

我认为问题是日期存储在 UTC 时区( 2018-02-15T23:33:30.000Z )中。

代码:

SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");      

Date fromDate = format.parse(from + " 00:00:00");
Date  toDate = format.parse(to + " 23:59:59");

Calendar cal = Calendar.getInstance();
cal.setTime(order.getOrderDate());
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));      
String strDate = sdf.format(cal.getTime());
Date orderDate = sdf.parse(strDate);

for(Order order : orders){
    if(orderDate.after(fromDate) || orderDate.equals(fromDate) && orderDate.before(toDate) || orderDate.equals(toDate)){
    //do something
    }
}
4

1 回答 1

1

java.util.Date 其中没有时区,因此解析和格式化订单日期没有意义。格式化将其转换为 aString并解析将其转换回 a Date,这是没有意义的,因为订单日期已经是一个Date对象。

您必须在第一个格式化程序(变量)中设置时区然后format解析fromto日期:它们将被设置为加尔各答时区的相应日期和时间 - 在这种情况下它是有效的,因为您有字符串并且想要将它们转换为日期。

然后,您使用额外的括号进行比较以避免任何歧义(如评论中所指出的)。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.timeAPI:

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/

于 2018-03-06T14:19:41.617 回答