0

I have the following JavaScript function to determine if a given date is the last day of the month:

function isLastDayOfMonth(date) {
    var parts = date.split(' ');
    var mo = parts[0];

    var month = parseInt(parts[0]);
    var day = parseInt(parts[1]);
    var year = parseInt(parts[2]);

    if (day == @DateTime.DaysInMonth(year, month)) {
        return true;
    }

    return false;
}

VisualStudio shows a syntax error, that year and month cannot be found in the current context (in the function call of DaysInMonth. I tried messing with the @, because I'm not sure what that's doing, to no avail. Visual Studio suggests that I start the parameter for DaysInMonth as: year: then I assume something else, but I'm not sure what. Can anyone help?

Anil
  • 2,539
  • 6
  • 33
  • 42
aquemini
  • 950
  • 2
  • 13
  • 32

3 Answers3

3

@DateTime.DaysInMonth(year, month) is a server side method. Javascript is ran client side (on the user's browser) so the two cannot directly interact in the way you are trying to do. Try the following Javascript instead

//month is 0 index in javascript aka Jan = 0
if(day === new Date(year, month+1, 0).getDate())

Method last date in month: https://stackoverflow.com/a/222439/597419

Community
  • 1
  • 1
Danny
  • 7,368
  • 8
  • 46
  • 70
  • This works, thanks. Can you explain why Date is client-side (and DateTime isn't), or is it just inherent? I'm really new at this. – aquemini Jan 17 '14 at 20:40
  • `DateTime` is a .NET object, `Date` is a Javascript object. All of the .NET code is interpreted on the server and sent to the user before any of the Javascript runs. Here is a reference of all Javascript objects http://www.w3schools.com/jsref/ – Danny Jan 17 '14 at 21:00
1

It appears that you are mixing asp .net MVC razor syntax in there. You can't run a c# function that receives javascript paramters, because they are just strings at this point.

You can generate part of your javascript code using razor, thats fine. But the razor is just creating a string to send to client. Its not live javascript code. The javascript is interpreted by the javascript engine in the browser.

CodeToad
  • 4,656
  • 6
  • 41
  • 53
0

Should you be using the Date() object by chance? I'm not sure what the @DateTime etc stuff is, but I think you want to use Date() for javascript.

Dan H
  • 606
  • 4
  • 6