I want to send C# DateTime object into Javascript. How can I accomplish that?
-
1Do 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.svanryckeghem– svanryckeghem2011-02-14 11:53:55 +00:00Commented Feb 14, 2011 at 11:53
Add a comment
|
4 Answers
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.
Comments
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
mauris
I'm assuming that the OT wants the DateTime object in C# to become DateTime object in Javascript
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
Sevin7
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#)