skip to main |
skip to sidebar
RSS Feeds
ASP.NET, JavaScript, Oracle and SQL articles and code.
ASP.NET, JavaScript, Oracle and SQL articles and code.
11:56 AM
Posted by Michael Heliso
Note: Please check JavaScript Utility Functions Note.
The following javascript function allows you to compare two dates. At this time only dd/mm/yyyy format is supported, but you can extend it very easily. The function will return -1 if first date is smaller than the second date, 1 if it is greater and 0 if both dates are equal.
/*Define the namespaces*/
var JavaScript = {};
JavaScript.Utils = {};
JavaScript.Utils.Date = {};
JavaScript.Utils.Date.Compare = function(firstDate, secondDate, format) {
if (!(typeof firstDate === "string") || !(typeof secondDate === "string"))
throw "Date must be a string.";
if (!format)
throw "invalid date format specified.";
var result = -1;
switch (format) {
case "dd/mm/yyyy":
{
var fdate = firstDate.match(/^(\d{2})\/(\d{2})\/(\d{4})$/i);
var ldate = secondDate.match(/^(\d{2})\/(\d{2})\/(\d{4})$/i);
if (parseInt(fdate[3]) < parseInt(ldate[3]))
result = -1;
else if (parseInt(fdate[3]) > parseInt(ldate[3]))
result = 1;
else
result = 0;
if (result == 0) {
if (parseInt(fdate[2]) < parseInt(ldate[2]))
result = -1;
else if (parseInt(fdate[2]) > parseInt(ldate[2]))
result = 1;
else
result = 0;
}
if (result == 0) {
if (parseInt(fdate[1]) < parseInt(ldate[1]))
result = -1;
else if (parseInt(fdate[1]) > parseInt(ldate[1]))
result = 1;
else
result = 0;
}
}
break;
}
return result;
};