Sunday, 5 May 2013

How to compare start and end time in JavaScript

Think of a form where we have entries for start and end time. There obviously we need to check that the end time should be after start time. Here at this point we will need to compare time and preferably that in client side(using Javascript).

In Javascript comparing date is quite simple. Just create date object of the dates and then using comparison operator you can compare the dates. But this is not that simple when it comes to compare two time strings. Javascript does not provide any direct way to compare time.

So I just found out a way to do so. Please take a look.

Here I am assuming that we have got time to compare in 24 hours format. So we do have time as hh:mm:ss or in some other format. First get the hour, minute and second part of this using string functions. And then go for the coding below. And if you don't have time in 24 hour format and its in 12 hour format as 06:30AM, then better convert it to 24 hour format, other wise it's hard to compare two time in 12 hour format.
//Set the extracted part of the time to variables. 
// If you dont have the second part then set it to 0.

 var startHour = extractedStartHour;
 var startMinute = extractedStartMinute;
 var startSecond = extractedStartSecond;

 var endHour = extractedEndHour;
 var endMinute = extractedEndMinute;
 var endSecond = extractedEndSecond;

 //Create date object and set the time to that
 var startTimeObject = new Date();
 startTimeObject.setHours(startHour, startMinute, startSecond);

 //Create date object and set the time to that
 var endTimeObject = new Date(startTimeObject);
 endTimeObject.setHours(endHour, endMinute, endSecond);

 //Now we are ready to compare both the dates
 if(startTimeObject > endTimeObject)
 alert('End time should be after start time.');
 alert('Entries are perfect.');

No comments :