Comparing dates is a good way to go about this, your problem is how you convert the strings to dates. You should not use the Date constructor (or Date.parse) to parse strings as it is largely implementation dependent and even strings consistent with ECMA-262 are not necessarily parsed correctly or give expected results.
Therefore, the first task is to parse the date strings. You can use a library, but if you only have one format to support a simple function will suffice. If the date and time are provided as separate parts, it's fairly simple to parse each part, either as a separate function or all in one, e.g.
/* @param {string} s - date string in format dd-MMM-yyyy
** @returns {Date} Date assuming local date
*/
function parseDate(s) {
var months = {jan:0,feb:1,mar:2,apr:3,may:4,jun:5,
jul:6,aug:7,sep:8,oct:9,nov:10,dec:11};
var b = s.match(/\w+/g) || [];
return new Date(b[2], months[b[1].slice(0,3).toLowerCase()], b[0]);
}
/* @param {string} s - time string in format hh:mmap
** @returns {Number} time converted to milliseconds
*/
function parseTimeToMs(s) {
var b = s.split(/\D/);
var h = b[0]%12 + (/pm$/i.test(s)? 12 : 0);
return h*3.6e6 + b[1]*6e4;
}
/* @param {string} ds - date string in format dd-MMM-yyyy
/* @param {string} ts - time string in format hh:mmap
** @returns {Date} Date assuming local date built from date and time strings
*/
function getDate(ds, ts) {
var d = parseDate(ds);
d.setMilliseconds(d.getMilliseconds() + parseTimeToMs(ts));
return d;
}
var startDate = '22-Apr-2016';
var endDate = '22-Apr-2016';
var startTime = '10:14 AM';
var endTime = '11:14 PM';
document.write('Start is: ' + getDate(startDate, startTime));
document.write('<br>End is : ' + getDate(endDate, endTime));
document.write('<br>Start before end? ' + (getDate(startDate, startTime) < getDate(endDate, endTime)));
body {
font-family: courier, monospace;
font-size: 80%;
}
Note that if using the relational operators <
and >
, the operands are coerced to number, however if doing equality comparisons with ==
or ===
, you'll always get false as they compare the operands as objects, which are only ever equal to themselves.
So you might want to always explicitly convert the Dates to number just to be sure, the unary +
operator is handy for that:
+getDate(startDate, startTime) < +getDate(endDate, endTime)
and
+getDate(startDate, startTime) == +getDate(endDate, endTime)