简体   繁体   中英

Java comparing dates

I have a database of suppliers, they rent car. Most people rent for a range of 2-3 days. on the database i have the rent start date/time stored in as datetime format. the rent end date is also in date time format.

suppose someone wants to rent the same car, if the requested range of date falls in one of the ranges of date the car is already rented out - how can i check the availability? i am using beans, servlets and jstl on the jsp pages.

i guess it should be a comparator?

If you're doing the comparisons in Java, the java.util.Date class already implements Comparable so you can just use its compareTo() method. But you can probably also do the comparisons in your database, using the < and > operators in SQL.

There's also the SQL OVERLAPS function, which lets you compare two date ranges to see if they overlap each other. That's probably simpler and more efficient, if your database supports it.

For example, supposing your table is called "reservations", you could do:

SELECT id FROM reservations
WHERE (DATE '2012-03-29', DATE '2010-04-01') OVERLAPS (start_date, stop_date)
  AND car_id = 12345;

And if that returns any rows, it means there's already a reservation for car 12345 that conflicts with that date range.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM