0

I want to send C# DateTime object into Javascript. How can I accomplish that?

1
  • 1
    Do you want to pass it for display, as data for further processing? Would it be part of a larger document? Are you concerned about converting .NET's DateTime to JavaScript Date object? Please clarify. Commented Feb 14, 2011 at 11:53

4 Answers 4

1

I don't know which method you use to "send" the value to JavaScript (include, HTTP response,...), but I usually format the DateTime to yyyy/MM/dd HH:mm:ss, pass it to the client, then I parse it with JavaScript using new Date(Date.parse({the date string}), which allows me to format it the way I want on the client-side, using the locale or other formatting constraints.

Sign up to request clarification or add additional context in comments.

Comments

0

Pretty much trivial:

<script type="text/javascript">
var strServerTime = "<%=DateTime.Now%>";
alert("server time: " + strServerTime);
</script>

However, what you want to do with that date? If only to display, the above should suffice otherwise explain and we'll see how to proceed.

2 Comments

I'm assuming that the OT wants the DateTime object in C# to become DateTime object in Javascript
@the that's up to him to answer.. in such case it get complicated as server time usually does not match the client time, neither in format nor in the time itself.
0

Convert it to a suitable string, and if you need to, have javascript parse it.

Comments

0
var myDate = DateTime.Now;
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Date", 
                String.Format(
                "var myDate = new Date({0}, {1}, {2}, {3}, {4}, {5}, {6});",
                myDate.Year,
                myDate.Month,
                myDate.Day,
                myDate.Hour,
                myDate.Minute,
                myDate.Second,
                myDate.Millisecond
                ), true);

Or

var javaBaseDate = new DateTime(1970, 1, 1);
var myDate = DateTime.Now;
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Date", 
  String.Format(
  System.Globalization.CultureInfo.InvariantCulture,
  "var myDate = new Date({0});",
   (myDate - javaBaseDate).TotalMilliseconds
   ), true);

1 Comment

I tested the first example and it works with one problem: The JavaScript Month range is from 0-11 instead of 1-12. To fix this simply use myDate.Month-1 on the server (C#)

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.