开发者

How can I parse my date ranges and then check for collisions?

I have to create a booking system type program, where the user inputs a user name (string) followed by the month, date and time they want to book, and开发者_如何学JAVA then the end month, date and time. So it'll look similar to:

John Jul 23 9 Jul 24 18

which is

user startMonth startDate startTime endMonth endDate endTime

I need to be able to implement this so that, I can check if any bookings collide, could someone please give me a guide in how to do this since I'm new to Java.

EDIT: I know how to parse the input, but I don't quite know how to use the date functions in java, and how that would help me check if any bookings collide.


To answer the question... ( start1 <= end2 and start2 <= end1 )

The java.util.Date wraps a long value. use getTime() to get that value, for comparisons.

See http://c2.com/cgi/wiki?TestIfDateRangesOverlap


In Java, parsing and formatting Date objects is handled by objects of type DateFormat, usually SimpleDateFormat.

Review the SimpleDateFormat documentation and try to imagine how you could use Date objects to see if there are any collisions.


Try using the Calendar object.


You need to parse the input, you can do it with String.split method or more sophisticated way, which I think is better, is by using java regex.

after parsing you can form a string which will contain the date and then to parse it with java date parser.


as maerics already wrote: SimpleDateFormat is your friend ...

split your input in 3 parts like SJuan76 suggested and feed both date parts to SimpleDateFormat's parse method ... that way you can get a Date object for both date parts ...

now to the booking part and that collision checking ...

i'd suggest you create your own class for a reservation or booking or however you want to call it.

you could use a LinkedList to store the objects ...

when you add an object to the list, keep the list sorted by start date ... that way you can see if an inserted object will collide wit another one ... find the location where to insert the new object ... look at the predecessor ... if the start date of the new object is before the predecessors end date we have a collision ... if the new end date is after the successors start date, we have a collision ... if there is no collision, insert the new object at this position in the list ...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜