Friday, December 15, 2006

Javascript code to get the year and quarter (20061, 20062...)

I think, I will focus on Javascript at this moment and I will post some of my javascript codes which might help some of new programmers. Code below is my answer for a question at http://www.experts-exchange.com/Web/Web_Languages/JavaScript/Q_22094132.html If you have any suggessions, please feel free to let me know and this will be advantage for the others.

function getQuater() {
if (document.getElementById('SOPeriodMode').value == 'Months') {
var startMonth = document.getElementById('nStartMth').value;
var startYear = document.getElementById('nStartYr').value;
var endMonth = document.getElementById('nEndMth').value;
var endYear = document.getElementById('nEndYr').value;
var quarterStr = '';

// if the same year
if (parseInt(endYear) == parseInt(startYear)) {
// check if the end month is bigger than start month
if (parseInt(endMonth) > parseInt(startMonth)) {
startQuarter = getQuarter(startMonth);
endQuarter = getQuarter(endMonth);
for(i = startQuarter; i <= endQuarter; i++) {
quarterStr += startYear + i + ',';
}
}
else {
alert('Month conflict : To month must be after From Month.');
document.getElementById('nEndMth').focus();
}
}
else if (parseInt(endYear) > parseInt(startYear)) {
// go through next year
startQuarter = getQuarter(startMonth);
endQuarter = getQuarter(endMonth);

// loop from the start quarter to the end of the year
for(i = startQuarter; i <= 4; i++) {
quarterStr += startYear + i + ',';
}

// start the first quarter of the new year until the end
for(i = 1; i <= endQuarter; i++) {
quarterStr += endYear + i + ',';
}
}
else {
alert('Year conflict : To year must be after From year.');
document.getElementById('nEndYr').focus();
}
}
// eliminate the ',' at the end
quarterStr = quarterStr.substr(0, (quarterStr.length -1));
alert(quarterStr);
}

function getQuarter(month) {
if ((month % 3) != 0)
quarter = (month / 3 - month % 3 / 3) + 1;
else
quarter = month / 3;
return quarter;
}

Note: This may not be the best code, since it covers only 1 year advance. If some of you can develop this code, please post it.

Thank you
Topgoodguy

No comments: