Keith Keith - 6 months ago 18
HTML Question

Get dates for last quarter and this quarter through Javascript

I'm trying to create a report that needs to get the dates for last quarter and this quarter through Javascript. The code worked last month but in March it doesn't work. It shows last quarter as this quarter and this quarter shows as next quarter. I am using datejs in this project. Here is the code I am using:

function thisQuarterDates(from, to) {
var month = Date.parse('today').toString('MM');
var quarterMonth = (Math.floor(month/3)*3)+1;
var year = Date.parse('today').toString('yyyy');

var quarterStartDate = (quarterMonth < 10) ? quarterMonth+'/1/' +year : quarterMonth+'/1/'+ year;
var quarterEndDate = Date.parse(quarterStartDate).add(2).months().moveToLastDayOfMonth().toString('M/d/yyyy');
var today = Date.parse('today').toString('M/d/yyyy');

document.getElementById(from).value = quarterStartDate;
document.getElementById(to).value = quarterEndDate;
}


function lastQuarterDates(from, to) {
var month = Date.parse('today').toString('MM');
var quarter = (Math.floor(month/3))+1;
var lastQuarter = (quarter > 1) ? quarter - 1 : lastQuarter = 4;
var year;
if (((((lastQuarter-1)*3)+1) < 10))
{
year = Date.parse('today').toString('yyyy');
}
else
{
year = Date.parse('today').add(-1).years().toString('yyyy');
}
var firstDate = ((((lastQuarter-1)*3)+1) < 10) ? (((lastQuarter-1)*3)+1) +'/1/'+ year : (((lastQuarter-1)*3)+1) +'/1/'+ year;
var lastDate = Date.parse(firstDate).add(2).months().moveToLastDayOfMonth().toString('M/d/yyyy');

document.getElementById(from).value = firstDate;
document.getElementById(to).value = lastDate;
}


Anyone know why it's incorrect or is there an easier way?

Answer

On the first function change

var quarterMonth = (Math.floor(month/3)*3)+1;

with

var quarterMonth = (Math.floor((month-1)/3)*3)+1;

and on the second function

var quarter = (Math.floor(month/3))+1;

with

var quarter = (Math.floor((month-1)/3))+1;

and I think it will be fine.

And on the second function I don't see the point of

((((lastQuarter-1)*3)+1) < 10)

a simple

(lastQuarter < 4)

will do the same job

Comments