3

I am trying to pass a datetime from C# to javascript.

I have converted my datetime at C# to FileTime (I am not sure, if this is the way to be done), and after that I passed this value to a ViewBag like this.

    ViewBag.minDate = minDate.ToFileTime();

Next I do this at javascript

    var date = new Date(Date.parse(<%=ViewBag.minDate%>));

Which becomes the following, but I get "Invalid Date"

var date = new Date(Date.parse(130014720000000000)

Do you know why is that, and How I can fix it?

Jim Blum
  • 2,656
  • 5
  • 28
  • 37

4 Answers4

5

Try this:

ViewBag.minDate = minDate.Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds;
anar khalilov
  • 16,993
  • 9
  • 47
  • 62
  • Thanks a lot man. Yes, this is what I used :), but forgot to choose as best answer. That solved my problem. Just to learn, and nothing more, why we create a new date 1-1-1970? I know that was the first date at a UNIX , but why we do that? And thanks a lot for helping me – Jim Blum Jan 24 '14 at 08:44
  • In javascript, "Date objects are based on a time value that is the number of milliseconds since 1 January, 1970 UTC." https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date But in C# there is no such thing. To normalize, we need to subtract this date from C# date. – anar khalilov Jan 24 '14 at 08:47
  • 1
    You are welcome. In stackoverflow, you learn things pretty fast. – anar khalilov Jan 24 '14 at 09:02
2

pass the date like this,

ViewBag.minDate =minDate.ToString("o")

and in your view,

var date = new Date("<%=ViewBag.minDate %>")
Mat J
  • 5,422
  • 6
  • 40
  • 56
2

or just:

ViewBag.SomeDate = DateTime.Now;

and then by using new Date(year, month, day, hours, minutes, seconds, milliseconds):

var date = new Date(<%:ViewBag.SomeDate.Year%>, <%:ViewBag.SomeDate.Month%>, <%:ViewBag.SomeDate.Day%>, <%:ViewBag.SomeDate.Hour%>, <%:ViewBag.SomeDate.Minute%>, <%:ViewBag.SomeDate.Second%>);
F34R
  • 128
  • 2
  • 5
1

You may try the following code.

var newDate = new Date(parseInt(ViewBag.minDate.substr(6)));
                    var day = ("0" + newDate.getDate()).slice(-2);
                    var month = ("0" + (newDate.getMonth() + 1)).slice(-2);
                    var date = newDate.getFullYear() + "-" + (month) + "-" + (day);
BPX
  • 888
  • 1
  • 8
  • 20