JSON date getting the wrong date
I am using JQUERY ajax to call an MVC method:
JQUERY:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Home/GetApplication/" + id,
dataType: "json",
data: '',
timeout: 10000,
success: function (obj) {
$('#Name').val(obj.Name);
$('#ApplicationIdentifier').val(obj.ApplicationIdentifier);
$('#Frequency').val(obj.FrequencyValue);
var d = new Date(parseInt(obj.BaseDate.substr(6)));
$('#BaseDate').val(d.getMonth() + '/' + d.getDay() + '/' + d.getFullYear());
},
error: function () {
return;
}
});
MVC Method:
[HttpPost]
public ActionResult GetApplication(int id)
{开发者_如何学运维
return Json(new Application
{
Name = "Testing",
ApplicationIdentifier = "123ABC",
FrequencyValue = 1,
FrequencyType = 1,
BaseDate = DateTime.Now
});
}
All of this works fine except the date appearing on my form is 4/5/2011 and it should be 5/13/2011. Am I missing something here? Thanks.
Working with dates and times between JavaScript and .NET can be difficult, and we usually handle this in our applications by always making the interaction in Unix Time:
[HttpPost]
public ActionResult GetApplication(int id)
{
DateTime unixTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Json(new Application
{
Name = "Testing",
ApplicationIdentifier = "123ABC",
FrequencyValue = 1,
FrequencyType = 1,
BaseDate = (DateTime.Now - unixTime).TotalMilliseconds
});
}
Now that your JavaScript application has the Unix Time, it can easily be converted to a Date (you are also formatting your date string incorrectly):
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Home/GetApplication/" + id,
dataType: "json",
data: '',
timeout: 10000,
success: function (obj) {
var d = new Date(obj.BaseDate);
var dateString = (d.getMonth() + 1) + '/' + d.getDate() + '/' + d.getFullYear();
$('#Name').val(obj.Name);
$('#ApplicationIdentifier').val(obj.ApplicationIdentifier);
$('#Frequency').val(obj.FrequencyValue);
$('#BaseDate').val(dateString);
},
error: function () {
return;
}
});
Also, I wouldn't return your EF entity to the front-end, only give it what it really needs. By using a dynamic
object, your types can be inferred here, and BaseDate becomes whatever type you give it:
[HttpPost]
public ActionResult GetApplication(int id)
{
DateTime unixTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Json(new {
Name = "Testing",
ApplicationIdentifier = "123ABC",
FrequencyValue = 1,
BaseDate = (DateTime.Now - unixTime).TotalMilliseconds
});
}
getMonth()
returns a value between 0 and 11, so just add 1 to it (source).
getMonth() returns 0-11; getDay() gets the day of the week!
The way I turn a \/Date(1234567889)\/
into a date that javascript can use is this: obj.BaseDate.slice(6, obj.BaseDate.length - 2);
Microsoft's date serialization causes the string, so you have to strip out everything other than the number.
That entire line would become var d = new Date(parseInt(obj.BaseDate.slice(6, obj.BaseDate.length - 2)));
精彩评论