- Level: Basic
- Skills Required: JavaScript Functions
Abstract:
Comparing two dates is a problem general enough to get special attention. When you develop a general purpose solution to such problems, you have a reusable piece of code that can save you hours of time.
Ground Work:
We will write a simple function that takes two well formed dates. The function will compare the dates and return:
- 0 if the dates are same
- -1 if the first one is an earlier date
- 1 if the first one is a later date
We will have to fix the date format. For this tutorial assume it to be mm-dd-yyyy where '-' is a separator. We will make extensive use of three JavaScript methods:
substring(start,
stop),
indexOf(searchString) and
lastIndexOf(searchString). They are used to extract a substring out of a string; to find position of a substring in a string and to find the last position of a substring in a string, respectively.
For example, suppose we have "12-10-2000" in the variable value1. To extract the date, month and year parts out of it, we will have to determine the first and last position of hyphen '-'. This can be done quite easily as shown below:
var firstIndex = value1.indexOf ;
var lastIndex = value1.lastIndexOf ;
month1 = value1.substring (0, firstIndex);
date1 = value1.substring (firstIndex+1, lastIndex);
year1 = value1.substring (lastIndex+1, value1.length);
Improving the Code:
There is always room for improvement. Our function assumes that the three parts of the date are separated by a hyphen. This may not always be true. So, it would be better if we pass a the separator string as a third argument to this function. Try this yourself as practice.