差 (日数) を取得して 2 つの日付を比較するには、次のプロトタイプ エクステンダー メソッドを使用できます。
注: さまざまなシナリオで (ヘルパーとして) 使用できる複数のメソッドにロジックを分散しました。
/** Gets the type (name) of the specified object.
*/
if (!Object.prototype.getType) {
Object.prototype.getType = function (obj) {
return ({}).toString.call(obj).match(/\s([a-z|A-Z]+)/)[1].toLowerCase();
}
}
/** Checks whether the object is Date.
*/
if (!Object.prototype.isDate) {
Object.prototype.isDate = function (date) {
return Object.getType(date) === 'date';
}
}
/** Gets the difference in days, between the given dates.
* If an invalid date is passed as a parameter, returns null.
*/
if (!Date.prototype.difference) {
Date.prototype.difference = function (date1, date2) {
if (!(Object.isDate(date1) && Object.isDate(date2))) return null;
var diff = Math.abs(date1.getTime() - date2.getTime()),
msInOneDay = 1000 * 60 * 60 * 24;
return Math.round(diff / msInOneDay);
}
}
/** Compares the date instance to the specified date value and returns an integer that indicates whether
* the instance is earlier than, the same as, or later than the specified date value.
* @return -1 if the specified date is invalid. 0 if they are the same. 1 if date1 is greater. 2 if date2 is greater.
*/
if (!Date.prototype.compareTo) {
Date.prototype.compareTo = function (date) {
if (!Object.isDate(date)) return -1; //not a Date
if (this == date) {
return 0;
} else if (this > date) {
return 1;
} else {
return 2; //date > this
}
}
}
使用法:
//Validate a date object
var dateIsValid = Object.isDate(date1);
//get the difference in days
var numOfDaysBetween = Date.difference(date1, date2);
//compare date to another
var comparison = date1.compareTo(date2);