Reputation: 119
I want to send C# DateTime object into Javascript. How can I accomplish that?
Upvotes: 0
Views: 1430
Reputation: 46947
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);
Upvotes: 0
Reputation: 923
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.
Upvotes: 1
Reputation: 12075
Convert it to a suitable string, and if you need to, have javascript parse it.
Upvotes: 0
Reputation: 66388
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.
Upvotes: 0