Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

Q819 How can I calculate how many hours per each month?

You are here: irt.org | FAQ | JavaScript | Date | Q819 [ previous next ]

Ignoring daylight saving changes then you can use the following:

<SCRIPT LANGUAGE="JavaScript"><!--
function makeArray() {
    this[0] = makeArray.arguments.length;
    for (i = 0; i<makeArray.arguments.length; i++)
        this[i+1] = makeArray.arguments[i];
}

var months = new makeArray('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
var days_per_month   = new makeArray(31,28,31,30,31,30,31,31,30,31,30,31);

function LeapYear(year) {
    if ((year/4)   != Math.floor(year/4))   return false;
    if ((year/100) != Math.floor(year/100)) return true;
    if ((year/400) != Math.floor(year/400)) return false;
    return true;
}

function y2k(number) { return (number < 1000) ? number + 1900 : number; }

var myDate = new Date(1999,0,1); // 1st January 1999


if (LeapYear(y2k(myDate.getYear())))
    days_per_month[2] = 29;
else
    days_per_month[2] = 28;

for (var month = 1; month<12+1; month++) {
    document.write(months[month] + ' ' + (days_per_month[month]*24) + ' hours<BR>');
}
//--></SCRIPT>

But then, if we've ignored daylight savings changes, then the number of hours per month is fixed just the same as the number of days per month, so we could use:

<SCRIPT LANGUAGE="JavaScript"><!--
function makeArray() {
    this[0] = makeArray.arguments.length;
    for (i = 0; i<makeArray.arguments.length; i++)
        this[i+1] = makeArray.arguments[i];
}

var months = new makeArray('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
var hours_per_month   = new makeArray(744,672,744,720,744,720,744,744,720,744,720,744);

function LeapYear(year) {
    if ((year/4)   != Math.floor(year/4))   return false;
    if ((year/100) != Math.floor(year/100)) return true;
    if ((year/400) != Math.floor(year/400)) return false;
    return true;
}

function y2k(number) { return (number < 1000) ? number + 1900 : number; }

var myDate = new Date(2000,0,1); // 1st January 1999

if (LeapYear(y2k(myDate.getYear())))
    hours_per_month[2] = 696;
else
    hours_per_month[2] = 672;

for (var month = 1; month<12+1; month++) {
    document.write(months[month] + ' ' + hours_per_month[month] + ' hours<BR>');
}
//--></SCRIPT>

©2018 Martin Webb