Developing Feather-Weight Webservices with JavaScript

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

« Custom and extended object classes · Extending the native String() class »
Google
 
Web Developing Featherweight Web Services with JavaScript
This is version 0.57b of this manual. It is a beta version with some gaps. We are grateful for feedback.

The code is the manual has not yet been fully tested against Internet Explorer. Bug reports are welcome.
An Elektrum Press Online