I am using the following function to find the last day of quarter of selected day. Now I am just adding 12*Date.WEEK but is not exactly what I want. Could you please have look and advice how to find the last day of quarter? I want to have the last day of quarter in date2.
function catcalc(cal) {
var date = cal.date;
var time = date.getTime();
var field = document.getElementById("x_Bis");
if (field == cal.params.inputField) {
field = document.getElementById("x_Von");
time -= 12*Date.WEEK; // substract one week
} else {
time += 12*Date.WEEK; // add one week 6*Date.DAY
}
var date2 = new Date(time);
field.value = date2.print("%d.%m.%Y");
I should keep the function structure and keep the name of variable. There are two calendar fields which are linked to each others. The user can just select from calendar any date (no clock time is necessary). The function is coming from http://cimanet.uoc.edu/logica/v2/lib/jscalendar-1.0/doc/html/reference.html.
Expanding @mplungjan proposal (and minding the JavaScript dumbness when working with dates). I'll use method chaining, so every next method will operate on what previous method have returned.
function getLastDayOfQuarter(date) {
var year = date.getFullYear();
var quarterEndings = [[3, 31], [6, 30], [9, 30], [12, 31]];
var toDateObj = function (dates) {
return new Date(year, dates[0] - 1, dates[1]);
};
var isBeforeEndDate = function (endDate) {
return endDate >= date;
}
date.setHours(0, 0, 0, 0);
return quarterEndings
.map(toDateObj)
.filter(isBeforeEndDate)[0];
}
getLastDayOfQuarter(new Date()).toDateString(); // "Mon Mar 31 2014"