.NET DateTime in Ajax
If we use ASP.NET web service or WCF with AJAX, the .NET DateTime is transfered in "/Date(1255329630000+0800)/" format (2009/10/12 14:40:30) between server and client browser. The format is UTC time, we are unable to use it directly in JavaScript, it should be converted first. The following sample using ExtJS and WCF shows how to convert between UTC time and JavaScript Date type.
Simple type example:
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class LearningService
{
[OperationContract]
[WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
public DateTime GetDate()
{
return new DateTime(2009, 10, 12, 14, 40, 30);
}
[OperationContract]
[WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
public void SetDate(DateTime date)
{
Debug.WriteLine(date, "Date");
}
}
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="AjaxBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service name="LearningService">
<endpoint address="" behaviorConfiguration="AjaxBehavior" binding="webHttpBinding" contract="LearningService"/>
</service>
</services>
</system.serviceModel>
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Default</title>
<link href="js/ext-2.2.1/resources/css/ext-all.css" rel="stylesheet" type="text/css" />
<script src="js/ext-2.2.1/adapter/ext/ext-base.js" type="text/javascript"></script>
<script src="js/ext-2.2.1/ext-all-debug.js" type="text/javascript"></script>
<script type="text/javascript">
var g_date;
Ext.onReady(function() {
var getDateButton = new Ext.Button({ text: "Get Date" });
getDateButton.on("click", function() {
Ext.Ajax.request({
method: "POST",
headers: { "Content-Type": "application/json; charset=utf-8" },
url: "LearningService.svc/GetDate",
success: function(response, options) {
g_date = toDate(Ext.decode(response.responseText).GetDateResult);
Ext.MessageBox.alert("Success", g_date.toLocaleString());
},
failure: function(response, options) {
Ext.MessageBox.alert("Failure", response.responseText);
}
});
});
getDateButton.render(Ext.getBody());
var setDateButton = new Ext.Button({ text: "Set Date" });
setDateButton.on("click", function() {
Ext.Ajax.request({
method: "POST",
headers: { "Content-Type": "application/json; charset=utf-8" },
url: "LearningService.svc/SetDate",
params: Ext.encode({ date: toWCFDate(g_date) }),
success: function(response, options) {
Ext.MessageBox.alert("Success", response.responseText);
},
failure: function(response, options) {
Ext.MessageBox.alert("Failure", response.responseText);
}
});
});
setDateButton.render(Ext.getBody());
});
function toDate(s) {
s = s.substr(1, s.length - 2)
return eval("new " + s);
}
function toWCFDate(d) {
var year = d.getUTCFullYear();
var month = d.getUTCMonth();
var date = d.getUTCDate();
var hours = d.getUTCHours();
var minutes = d.getUTCMinutes();
var seconds = d.getUTCSeconds();
var ms = d.getUTCMilliseconds();
var value = Date.UTC(year, month, date, hours, minutes, seconds, ms);
return "/Date(" + value + ")/";
}
</script>
</head>
<body>
</body>
</html>
Complex type example:
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class LearningService
{
[OperationContract]
[WebGet(BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
public Person GetPerson()
{
return new Person()
{
Name = "Will Smith",
BirthDate = new DateTime(2009, 10, 12, 14, 40, 30)
};
}
[OperationContract]
[WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
public void SetPerson(Person person)
{
Debug.WriteLine(string.Format("{0} {1}", person.Name, person.BirthDate), "Person");
}
}
[DataContract]
public class Person
{
[DataMember]
public string Name { get; set; }
[DataMember]
public DateTime BirthDate { get; set; }
}
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="AjaxBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service name="LearningService">
<endpoint address="" behaviorConfiguration="AjaxBehavior" binding="webHttpBinding" contract="LearningService"/>
</service>
</services>
</system.serviceModel>
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Default</title>
<link href="js/ext-2.2.1/resources/css/ext-all.css" rel="stylesheet" type="text/css" />
<script src="js/ext-2.2.1/adapter/ext/ext-base.js" type="text/javascript"></script>
<script src="js/ext-2.2.1/ext-all-debug.js" type="text/javascript"></script>
<script type="text/javascript">
var g_person;
Ext.onReady(function() {
Ext.Ajax.request({
method: "GET",
headers: { "Content-Type": "application/json; charset=utf-8" },
url: "LearningService.svc/GetPerson",
success: function(response, options) {
g_person = Ext.decode(response.responseText).GetPersonResult;
g_person.BirthDate = toDate(g_person.BirthDate);
Ext.MessageBox.alert("Success", g_person.Name + " " + g_person.BirthDate.toLocaleString());
},
failure: function(response, options) {
Ext.MessageBox.alert("Failure", response.responseText);
}
});
var button = new Ext.Button({ text: "Post a person" });
button.on("click", function() {
g_person.BirthDate = toWCFDate(g_person.BirthDate);
Ext.Ajax.request({
method: "POST",
headers: { "Content-Type": "application/json; charset=utf-8" },
url: "LearningService.svc/SetPerson",
params: Ext.encode({ person: g_person }),
success: function(response, options) {
Ext.MessageBox.alert("Success", response.responseText);
},
failure: function(response, options) {
Ext.MessageBox.alert("Failure", response.responseText);
}
});
});
button.render(Ext.getBody());
});
function toDate(s) {
return eval("new " + s.substr(1, s.length - 2));
}
function toWCFDate(d) {
var year = d.getUTCFullYear();
var month = d.getUTCMonth();
var date = d.getUTCDate();
var hours = d.getUTCHours();
var minutes = d.getUTCMinutes();
var seconds = d.getUTCSeconds();
var ms = d.getUTCMilliseconds();
var value = Date.UTC(year, month, date, hours, minutes, seconds, ms);
return "/Date(" + value + ")/";
}
</script>
</head>
<body>
</body>
</html>