Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 265
Keith Avatar asked Mar 23 '12 14:03

Keith


People also ask

How do you get the current quarter in typescript?

var today = new Date(); var quarter = Math. floor((today. getMonth() + 3) / 3); var nextq; if (quarter == 4) { nextq = new Date (today. getFullYear() + 1, 1, 1); } else { nextq = new Date (today.


1 Answers

Simple generic solution in pure JS.
First calculate quarter number:

const quarter = Math.floor((today.getMonth() / 3));
const today = new Date();

Next, current quarter:

const startFullQuarter = new Date(today.getFullYear(), quarter * 3, 1);
const endFullQuarter = new Date(startFullQuarter.getFullYear(), startFullQuarter.getMonth() + 3, 0);

Previous quarter

const startFullQuarter = new Date(today.getFullYear(), quarter * 3 - 3, 1);
const endFullQuarter = new Date(startFullQuarter.getFullYear(), startFullQuarter.getMonth() + 3, 0);

Add or subtract 3's per quarter in expression new Date(today.getFullYear(), quarter * 3 - x, 1) to get future or past quarters.

like image 55
Walter Luszczyk Avatar answered Nov 04 '22 22:11

Walter Luszczyk