views:

45

answers:

2

Hi,

I'm having problems with the following JavaScript code. I coded in the comments what's happening:

function fetchMaand() {
    var dteBegin, dteEnd, clsDate, monthsAhead;
    monthsAhead = $('#dteMaand').val(); // dteMaand's value = -3 for example
    clsDate = new Date(); // Current time
    clsDate.setMonth(clsDate.getMonth() + monthsAhead); // Here it starts doing weird (date is somewhere in 2015 ??)
    clsDate.setDate(1);
    dteBegin = formatBIN(clsDate);
    clsDate.setDate(30);
    dteEind = formatBIN(clsDate);
    $.get("jsexec/agenda_array_gebeurtenissen.cfm", {
        begindatum : dteBegin,
        einddatum  : dteEind
    } , fillMaandBox);
}

function fillMaandBox(result) {
    // Handle data
}

function formatBIN(date) {
    return date.getFullYear() + "-" + to2(date.getMonth() + 1) + "-" + to2(date.getDate())
}

function to2(i) {
    return  ("00" + i).substr(("00" + i).length - 2 , 2);
}

Could you please help me out? This is part of a calendar website from me, and I am trying to make a combobox with the month (dteMaand) and if you make a change to that combo, the first function is called (fetchMaand() )

The code is supposed to do the following:

  • A user changes the combobox with a month (current month is selected), and the value of the combobox is the relative index (eg. this month is July, May will be -2)
  • The function fetchMaand will be called in the onchange event.

My real question is acutally on this one "Why is the date somewhere in 2015?". Wat am I doing wrong in this code?

Thanks!

Yvan

A: 

Not sure if this is your problem, but I know starting from the current date in JavaScript and then setting the month is not always a good idea. E.g., if the current date is Jan 31st, and you add 1 to the month, you'll go right past February and into March. This result (March one month ahead of January) is often not what you want.

I don't really know from what you posted what your code is supposed to do, so I can't be sure if this is part of the problem. But in particular it looks like you're trying to set the date to the first of the following month (at least when monthsAhead is 1). Calling setMonth before setDate won't do this (in my example it'd give March 1st. You'd be better off doing the setDate before the setMonth.

Tim Goodman
Good point: it's safe however if you 'setDate(1)' first.
Pointy
+1  A: 

Not 100% sure this'll help but I'd change:

monthsAhead = $('#dteMaand').val();

to

monthsAhead = parseInt($('#dteMaand').val(), 10);

Also @Tim is correct: you should do that setDate(1) before bumping the months forward or backwards.

Pointy
This was exactly my problem! I concatenated "-3" and the current month index, giving "6-3", which is an invalid integer.Many thanks for your response!!Yvan
Yvan JANSSENS