Spring JPA Query to Check if the Current Date is Between a Range of Two Dates
The following code shows you how to check if the current date is between a range of two dates using the Spring Data JPA query method:
Price Entity class:
public class OfferedPrice {
private String id;
private double currentPrice;
private Date fromDate;
private Date toDate;
//getter setter methods
}
JPA Query method to find the offered price on the current date by searching between a range of two dates:
Date serverCurrentDateTime = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
//timezone of your database
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String currentDateTimeStr = dateFormat.format(serverCurrentDateTime);
Date now = null;
try {
now = dateFormat.parse(currentDateTimeStr);
} catch (ParseException e) {
e.printStackTrace();
}
OfferedPrice offeredPrice = offeredPriceRepository.findByFromDateLessThanEqualAndToDateGreaterThanEqual(now, now);