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?

4

4 Answers 4

5

Try this:

ViewBag.minDate = minDate.Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds;
Sign up to request clarification or add additional context in comments.

3 Comments

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
In javascript, "Date objects are based on a time value that is the number of milliseconds since 1 January, 1970 UTC." developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… But in C# there is no such thing. To normalize, we need to subtract this date from C# date.
You are welcome. In stackoverflow, you learn things pretty fast.
2

pass the date like this,

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

and in your view,

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

2 Comments

Can you check the generated javascript in the browser? This should work.
I was wrong. The invalid date was produced by something else I had wrong. Thanks a lot. Just upvoted :)
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%>);

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.