0

I would like to convert a string to date object and add in the last three month from the date to form a quarterly report using javascript.

For example, I am receiving the following string "August-2010" using the following

var currDate = "August-2010";

Based on the date, I will need to compute the last three months from the current date, for example: July-2010 June-2010 May-2010

Lastly, I will need to format that result into an array in the following format:

[May,Jun,Jul,Aug];

How should I do it in Javascript?

  • 3
    Is this a homework assignment? If yes, than tag appropriately. – Jakub Konecki Aug 27 '11 at 10:48
0

This function returns the month+year of the last X months:

function getPastXMonths(theDate, X) {

    var d = new Date(Date.parse(theDate.replace('-', ' 1 ')));
    var out = [];
    var i = 0;

    while (i++ < X) {
        out.push([
        'January','February','March','April','May','June','July','August','September','October','November','December'
        ][d.getMonth()] + '-' + d.getFullYear());
        d.setMonth(d.getMonth() - 1);
    }

    return out;
}

var months = getPastXMonths('August-2010', 3);
alert(months.join('\n'));

http://jsfiddle.net/SLcNJ/4/

| improve this answer | |
0
var Months = ["Jan", "Feb", "Mar", "Apr", "May", "June", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

var d = new Date(Date.parse("August-2010"));
var CurrentMonth = d.getMonth();
var NumberOfMonthsBack = 4;
var Quarter = [];

for(x = 0; x < NumberOfMonthsBack; x++) {
    if(CurrentMonth == -1) {
        CurrentMonth = 11;
    }
    Quarter.unshift(Months[CurrentMonth--]);
}

alert(Quarter);
| improve this answer | |
  • I tried this line: var d = new Date(Date.parse("August-2010")) in w3school code testing page but I get "invalid" when I tried "document.write(d.toString())" – Mr.J4mes Aug 27 '11 at 11:09
  • I've just tried it on w3school and it works fine. But really you shouldn't use the document.write() method after a page has already been loaded. Just use alert() to echo simple test data. – Gary Willoughby Aug 27 '11 at 12:51
  • new Date(Date.parse("August-2010")) doesn't work in all browsers. Try it in firefox. – James Aug 27 '11 at 13:03
  • Good point J-P! It's not that the method doesn't work, it's that the parsing is better in some browsers than others. Obviously firefox's is not as good as Chrome's. I would still recommend a dedicated parsing library though just in case the format of the date changes in time. Maybe something like datejs.com – Gary Willoughby Aug 27 '11 at 13:13
0

If the format for currDate is fixed, I guess you will have to process your string and put a number of if and else to get the final result. For example,

<script type="text/javascript">
    var monthArray = ["January","February","March","April","May","June","July","September","October","November","December"];
    var currDate = "August-2010";
    var month = currDate.substring(0,currDate.indexOf("-"));
    var year  = parseInt(currDate.substr(currDate.indexOf("-")+1));
    int i;
    for (i = 0 ; i < 12 ; i++) {
        if (month == monthArray[i]) break;
    }
    var resultArray = []; //This is the array that contain 4 months
    resultArray[3] = month.substring(0,3); //The last element of the array should be the month in currDate, I suppose the format is the 1st 3 letters of the month

    for (int j = 1 ; j < 4 ; j++) {
        var theYear = year;
        var k = i - j;
        if (k < 0) {
            k+=12;
            theYear--;
        }
        var theMonth = monthArray[k];
        resultArray[3-i] = theMonth.substring(0,3);
        alert(theMonth+"-"+theYear); // You get the 3 previous month here (e.g. July-2010, etc...)
    }

</script> 
| improve this answer | |
0
var getLastThreeMonths = (function(){

    var months = [
            'Jan','Feb','Mar','Apr','May','Jun',
            'Jul','Aug','Sep','Oct','Nov','Dec'
        ],
        monthsAsObj = (function() {
            var r = {}, l = 12;
            while (l--) r[months[l]] = l;
            return r;
        }());

    return function getLastThreeMonths(date){

        var month = date.split('-')[0],
            monthIndex = monthsAsObj[month.slice(0,3)];

        return months.slice(monthIndex - 3, monthIndex);

    };

}());

getLastThreeMonths('August-2010'); // => ["May", "Jun", "Jul"]
| improve this answer | |
  • @Gary, is it likely to change? The OP mentioned no such possibility. – James Aug 27 '11 at 13:02
0
var searched, iFound, res, months = [ 'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec' ];
var currDate = "August-2010";

// IE does not implement Arrays' indexOf, here is a workaround :
if(!Array.prototype.indexOf){
   Array.prototype.indexOf = function(expected){
     for(var i = 0; i < this.length; i++){
        if(this[i] === expected) return i;
     }
     return -1;
   }
}

searched = currDate.substring(0,3); // lets take the only 3 first letters of currDate
iFound = months.indexOf(searched); // we look for the index of the month in the array
if(iFound >= 0){ // if the month was found
   res = months.slice(iFound-3, iFound+1); // slice copies a portion of the array. Here, it copies from iFound-3 to iFound+1 (excluded)
   console.log(res);
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.