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.

Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61
Zoe
  • 13
  • 1
  • 6

1 Answers1

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");
    }
});
TanvirArjel
  • 30,049
  • 14
  • 78
  • 114
  • 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. – Tyler Roper Jan 31 '19 at 03:58
  • `"modelFromDate is not defined"` this is because he did not use `@ `simple before the variable accessing in javascript. – TanvirArjel Jan 31 '19 at 04:00
  • Hey, I've tried adding a @ and it made no difference – Zoe Jan 31 '19 at 20:06
  • @Zoe Have debugged it properly to see the value of `modelFromDate` in js code? – TanvirArjel Feb 01 '19 at 02:31