Comparing values from multiple jQuery UI Datepickers

Intro

The other day I was working on a project for a client at Paradox Labs which required a form where a user could enter a start date and time for an event as well as an end date and time. To accomplish this task, I used Trent Richardson‘s wonderful Timepicker add-on. This tutorial was written using it, but the code should also work with a standard datepicker since I am actually hooking into its events.

If you just want to see the code, you can skip to the solution or view the jsFiddle fiddle.

The problem

When using multiple datepickers, it may be necessary to make sure that the user has chosen the correct dates and times. Naturally, an event could span one or more days or hours but it is highly unlikely that it would start now or in the future and end in the past without a time machine. Likewise, an event would not start after it has already ended. How do we prevent this from happening?

The solution

By converting the dates and times selected to milliseconds and comparing those values, a time-bending paradox is averted. Here is what I came up with:

If you look closely at the code (in particular the CheckTimes function), you’ll see that I am using the JavaScript object method Date.parse to do the conversion along with some standard operators (“>=” and “<=”) to do the comparison. Problem solved! Play with the fiddle to see how it works. (The rest of the code is provided for demonstration purposes.)

References

Notes

This brief tutorial assumes that you are at least somewhat familiar and comfortable with the jQuery¬†JavaScript framework. If you need some help, don’t hesitate to contact me or – even better – post your question on StackOverflow or the WordPress StackExchange (wherever most appropriate).