1

I am trying to convert a C# DateTime variable into something that is able to be passed into a Javascript function through NewtonSoft.Json.

At the moment what I am using is:

var jsonSettings = new JsonSerializerSettings();
jsonSettings.DateFormatString = "dd/MM/yyy hh:mm:ss";
string modelFromDate = JsonConvert.SerializeObject(@Model.FromDate, jsonSettings);

However this does not seem to be working since when I use Chrome Dev Tools I get the error that

modelFromDate is not defined

in the following code:

$(".go").on("click", function () {
    if (new Date(modelFromDate) < new Date(1994, 1, 1)) {
        alert("invalid date");
    }
});

I am using ASP.NET Core MVC.

0

1 Answer 1

0

modelFromDate is not defined

This is because you did not use @ simple before the C# variable accessing in JavaScript.

Morevoer you can use Date.parse. It will return number of milliseconds, then you need to wrap a Date constructor around it as follows:

$(".go").on("click", function () {
    var jsFromDate = new Date(Date.parse(@modelFromDate));
    if (jsFromDate  < new Date(1994, 1, 1)) {
        alert("invalid date");
    }
});
Sign up to request clarification or add additional context in comments.

4 Comments

OP's problem is not formatting the date, it's "modelFromDate is not defined". From what I can tell they're declaring the date variable in C# and trying to access it in JavaScript.
"modelFromDate is not defined" this is because he did not use @ simple before the variable accessing in javascript.
Hey, I've tried adding a @ and it made no difference
@Zoe Have debugged it properly to see the value of modelFromDate in js code?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.