Comparing Time using Javascript
I am having a start time,start date and end date,end time on my web page.I need to ensure that if the start date and end date is equal then the end time must be greater than start time and if end date is greater than start date then user can able to enter any tim开发者_JS百科e.How can I achieve this validation?
I would highly highly recommend something like Datejs. This should give you a starting point though:
// get the values from your form
var startDate = $('input[name=startDate]').val(),
endDate = $('input[name=endDate]').val(),
startTime = $('input[name=startTime]').val(),
endTime = $('input[name=endTime]').val()
If you decide to use Datejs you should parse the values from the input field using Date.parse(startDate)
. Check out the Getting Started. If you decide not to use DateJs, you could append getTime() to the startTime var. (e.g. - endTime.getTime() < startTime.getTime()
)
var error = '';
// if the start date is after the end date
if (startDate > endDate){
var error = error + 'Your start date is after your end date.';
}
// if the start date and end date are the same -- and end time is before the start time
else if(startDate == endDate && endTime < startTime){
var error = error + 'Your end time is before your start time.';
};
// handle any errors
if(error.length){
alert(error);
};
It's good to know how stuff works, and you could benefit from building this yourself without depending on a framework. Should you want to try it, assuming you have simple strings for your dates and times, you could start with this:
var dateStart = "Oct 13, 2010";
var timeStart = "10:13";
var dateEnd = "Nov 11, 2011";
var timeEnd = "14:56";
var startDate = new Date(dateStart + " " + timeStart);
var endDate = new Date(dateEnd + " " + timeEnd);
alert(startDate > endDate);
For real code see http://jsbin.com/oponu3/edit
If you are just using this to compare time, then this would work:
var myDate = "Oct 13, 2010";
var timeStart = "10:13";
var timeEnd = "14:56";
var startDate = new Date(myDate + " " + timeStart);
var endDate = new Date(myDate + " " + timeEnd);
alert(startDate > endDate);
You could enhance this by checking for illegal date values. Check the W3C reference for the JavaScript Date object for this: http://www.w3schools.com/js/js_obj_date.asp
// calculate difference (added 2012-04-04)
var milliseconds = Math.abs(startDate.getTime() - endDate.getTime());
var seconds = milliseconds / 1000;
var minutes = seconds / 60;
var hours = minutes / 60;
// etc etc etc
精彩评论