Monday, September 19, 2011

Servoy TIP: Getting Current Quarter Date Range

I do a lot of applications where users want reports or lists that take a date in the current record and filter or find all the records "In This Quarter".

The calculation isn't all that difficult - but it's a cool time saver. Below, I've actually created 3 functions - so you can use the quarter start date, end date, or date range.


/**
 * Return the starting quarter date for a given date
 * 
 * @param {Date} inputDate
 * @return {Date}
 */
function getQuarterStartDate(inputDate) {
if(!inputDate) { return null; }
var inDate = new Date(inputDate);
var mo = inDate.getMonth() + 1; //remember JS months are 0-11!
var yr = inDate.getFullYear();
if(mo > 9) {
return new Date(yr, 10, 1);
} else if (mo > 6) {
return new Date(yr, 7, 1);
}  else if (mo > 3) {
return new Date(yr, 4, 1);
} else {
return new Date(yr, 1, 1);
}
}


/**
 * Return the ending quarter date for a given date
 * 
 * @param {Date} inputDate
 * @return {Date}
 */
function getQuarterEndDate(inputDate) {
if(!inputDate) { return null; }
var inDate = new Date(inputDate);
var mo = inDate.getMonth() + 1; //remember JS months are 0-11!
var yr = inDate.getFullYear();
if(mo > 9) {
return new Date(yr, 12, 31);
} else if (mo > 6) {
return new Date(yr, 9, 30);
}  else if (mo > 3) {
return new Date(yr, 6, 30);
} else {
return new Date(yr, 3, 31);
}
}

/**
 * Return a search string properly formatted for the start/end quarter dates
 * 
 * @param {Date} inputDate
 * @return {String}
 */
function getQuarterRange(inputDate) {
if(!inputDate) { return null; }
var sDate = getQuarterStartDate(inputDate);
var eDate = getQuarterEndDate(inputDate);
var theFormat = i18n.getDefaultDateFormat();
if(sDate && eDate) {
return utils.dateFormat(sDate,theFormat) +
"..." + utils.dateFormat(sDate,theFormat) + "|" + theFormat;
} else {
return null;
}
}

No comments:

Web Analytics