It happens once in a while that I come across a web-form that asks for 2 dates to indicate a time span. I know it can give quite an amount of trouble to program such a date range, especially due to validation. Luckily there can be tons of packages found on GitHub for frameworks like jQuery or AngularJS. What I didn’t found was a simple data type, so without any form of presentation, to handle and validate those ranges.
Recently I had to work with time spans that were not to overlap with each other and had to be subjected to all kinds of calculations. This inspired me to create a value object for it. Beware, the DateRange object.
Installation
This package is available via Bower:
1 2 3 |
bower install --save date-range |
Or NPM:
1 2 3 |
npm install --save date-range |
Usage
Creating a date range is as easy as creating any object. When the passed dates do not form a valid range pair an error will be thrown.
1 2 3 4 5 |
var range = new DateRange(new Date(2000, 0, 1), new Date(2015, 0, 1)); new DateRange(new Date(2018, 0, 1), new Date(2015, 0, 1)); // Throws error |
This object can now give you any info about the range you like.
1 2 3 4 5 6 7 8 9 10 11 |
console.log(range.getDates(); // logs [Date, Date, Date, ...] console.log(range.getMondays(); // logs [Date, Date, Date, ...] console.log(range.getFridayThe13ths(); // logs [Date, Date, Date, ...] console.log(range.getYears(); // logs [2000, 2001, 2002, ...] console.log(range.getLeapYears(); // logs [2000, 2004, 2008, ...] |
Calculating with a date range
Now, especially when the validation of you date range depends on other dates or ranges, some of the next methods might be useful to achieve this.
1 2 3 4 5 6 7 8 9 10 11 |
console.log(range.contains(new Date(2004, 6, 24)); // logs true console.log(range.indexOf(new Date(2004, 6, 24)); // logs 7954 console.log(range.doesIntersect(range2)); // logs true console.log(range.contains(range2); // logs false console.log(range.intersection(range2)); // logs DateRange |
Documentation
Full documentation can be found on GitHub.
Issues can also be filed there.