Date changed to local time when being passed using JSON
I have a page that displays data from an object. I'm loading the object server side, and passing the results through an AJAX call with json. There is a date property that is part of the object. For some reason, the date is being changed. It looks like it is trying to take into account the timezone I'm in and subtracting 4 hours from the date (I'm in EST, -4 difference from GMT).
When I click a "Display" button for a message, it makes an AJAX call to load the data for that message, and then displays it.
Here's my javascript code:
function onBtnDisplayClicked(id)
{
$.ajax({
type: "POST",
url: "<%= Url.Action("GetMessage") %>?id=" + id.toString(),
success: function(data) { bindItem(data); },
dataType: "json",
contentType: "application/json; charset=utf-8"
});
}
function b开发者_高级运维indItem(data)
{
$("#MessageID").val(data.MessageID);
//Create a Date object from JSON date format - ex: (1230807660000-4000)
var messageDate = new Date(parseInt(data.MessageDate.replace(/\/Date\((\d+)\)\//, '$1')));
//Format date using DateFormat plugin (http://jacwright.com/projects/javascript/date_format)
$("#txtMessageDate").val(messageDate.format('m/d/Y H:i'));
}
And here's my server side code:
public JsonResult GetMessage(int id)
{
Message msg = new Message();
msg.LoadByPrimaryKey(id);
var data = new
{
MessageID = msg.MessageID.Value,
MessageDate = msg.MessageDate.Value
};
return new JsonResult() { Data = data };
}
This will work correctly on my local environment, but not on my production environment. In my local environment, the server time is set to EST (2:00 PM). On production, the server time is set to GMT (6:00 PM).
So if I'm trying to display "09/01/2010 09:00 AM", it will display correctly on my local environment, but on production it displays as "09/01/2010 05:00 AM". I'm not sure why it's doing this.
It is likely doing this because it knows what timezone the date is coming from, so technically speaking they both represent the same point in time with regards to your timezone...
I'm not entirely sure how you would do it, but you need to override the timezone used when formatting the string when presenting the date to the UI. If you have access to the code in that DateTime plugin, then I suspect this is the place to address the problem.
Sorry its not a practical answer; I only get the theory as I have little to no JSON/AJAX experience these days.
精彩评论