Julian days and delta days with Date.prototype JavaScript extension
Date.prototype.julianDays() and Date.prototype.deltaDays()
/* (c) APV, Artistic License 2, retain this notice */
Date.prototype.julianDays = function () {
if ( this.jd ) return this.jd;
var y = this.getFullYear();
var m = this.getMonth() + 1;
var d = this.getDate();
/*
Julian Days conversion algorithm is from
"Astronomical Algorithms," 1991, page 61,
Jean Meeus. Found via Peter Baum.
*/
if ( m < 3 ) {
m += 12;
y--;
}
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() );
}
Sample usage
(JavaScript error)
<blockquote id="days_left">
(JavaScript error)
</blockquote>
<script type="text/javascript">//<![CDATA[
var now = new Date();
var last_day_of_year = new Date(now.getFullYear(), 11, 31);
var delta = last_day_of_year.deltaDays(now);
var plural = delta == 1 ? 0 : 1;
var note = document.createTextNode("There " +
( plural ? "are " : "is " ) +
delta + " day" +
( plural ? 's' : '' ) +
" left in the year."
);
var bq = document.getElementById("days_left");
bq.removeChild(bq.firstChild);
bq.appendChild(note);
//]]> </script>