Extending the native Date() class
You can see this class in use in Using JS code libraries, part 2.
/*
Code from "Developing Featherweight Web Services with JavaScript"
http://feather.elektrum.org/
(c)An Elektrum Press, retain this notice
License: http://feather.elektrum.org/appendix/licenses.html
*/
Date.prototype.julianDays = function () {
if ( this.jd ) return this.jd;
var y = this.getFullYear();
var m = this.getMonth() + 1;
var d = this.getDate();
// this is a fairly well know algorithm for converting
if ( m < 3 ) {
m += 12;
y--;
}
// Julian Days conversion algorithm is from "Astronomical Algorithms,"
// 1991, page 61, Jean Meeus. Found via Peter Baum.
this.jd =
Math.floor( 365.25*( y + 4716 ) ) +
Math.floor( 30.6001*( m + 1 ) ) + d + 2 -
Math.floor( y/100 ) +
Math.floor( Math.floor( y/100 ) / 4 ) - 1524.5;
return this.jd;
}
Date.prototype.deltaDays = function ( date2 ) {
// might want to try/throw custom errors here
return Math.abs( this.julianDays() - date2.julianDays() );
}
Date.namesOfMonths = new Array( 'January' ,'February'
,'March' ,'April' ,'May'
,'June' ,'July','August'
,'September' ,'October'
,'November' ,'December' );
Date.prototype.getMonthName = function( monthIndex ) {
if ( ! ( monthIndex && typeof( monthIndex ) == 'number' &&
monthIndex >= 0 && monthIndex < 12
) )
monthIndex = this.getMonth();
return Date.namesOfMonths[monthIndex];
};
Live tests
All original content is ©2004-2005 an elektrum press, all
rights reserved. For code use, please see Licenses and terms of use.
