java.util.Date
doesn't have a timezone in it, so there's no point in parsing and formatting the order date. Formatting converts it to a String
and parsing converts it back to a Date
, which is pointless, because the order date is already a Date
object.
You must set the timezone in the first formatter (the format
variable), and then parse the from and to dates: they'll be set to the respective dates and times at Kolkata's timezone - in this case it's valid, because you have strings and want to convert them to dates.
Then you make your comparison using extra parenthesis to avoid any ambiguities (as pointed in the comments).
And there's no point in setting the Date
to a Calendar
, just to get it back later - the Calendar
instance has no purpose in your code.
And the call to getOrderDate
shouldn't be inside the for
loop?
The full code will be like this:
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)) ) {
....
}
}
If you have Java >= 8, it's better to use the 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))) {
...
}
}
It's a different code because this API introduces new types and concepts, but it's quite a improvement from the previous API (Date
and Calendar
are messy, buggy and outdated).
Take some time to study this API, it's totally worth it: https://docs.oracle.com/javase/tutorial/datetime/