我一直在努力解决这个问题,因为上述答案都没有真正帮助我。我正在使用 jquery 周历,需要我的日期在服务器上和页面上本地获取时区信息。经过一番挖掘,我想出了一个可能对其他人有所帮助的解决方案。
我正在使用 asp.net 3.5,与 2008、asp.net MVC 2 和 jquery 周历相比,
首先,我使用的是 Steven Levithan 编写的库,它有助于在客户端处理日期,Steven Levithan's date library。 isoUtcDateTime 格式非常适合我的需要。在我的 jquery AJAX 调用中,我使用带有 isoUtcDateTime 格式的库提供的格式函数,当 ajax 调用命中我的操作方法时,日期时间类型设置为本地并反映服务器时间。
当我通过 AJAX 将日期发送到我的页面时,我通过使用 "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'zzzz" 格式化日期来将它们作为文本字符串发送。这种格式很容易在客户端使用
var myDate = new Date(myReceivedDate);
这是我的完整解决方案减去 Steve Levithan 的源代码,您可以下载:
控制器:
public class HomeController : Controller
{
public const string DATE_FORMAT = "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'zzzz";
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
}
public ActionResult About()
{
return View();
}
public JsonResult GetData()
{
DateTime myDate = DateTime.Now.ToLocalTime();
return new JsonResult { Data = new { myDate = myDate.ToString(DATE_FORMAT) } };
}
public JsonResult ReceiveData(DateTime myDate)
{
return new JsonResult { Data = new { myDate = myDate.ToString(DATE_FORMAT) } };
}
}
Javascript:
<script type="text/javascript">
function getData() {
$.ajax({
url: "/Home/GetData",
type: "POST",
cache: "false",
dataType: "json",
success: function(data) {
alert(data.myDate);
var newDate = cleanDate(data.myDate);
alert(newDate);
sendData(newDate);
}
});
}
function cleanDate(d) {
if (typeof d == 'string') {
return new Date(d) || Date.parse(d) || new Date(parseInt(d));
}
if (typeof d == 'number') {
return new Date(d);
}
return d;
}
function sendData(newDate) {
$.ajax({
url: "/Home/ReceiveData",
type: "POST",
cache: "false",
dataType: "json",
data:
{
myDate: newDate.format("isoUtcDateTime")
},
success: function(data) {
alert(data.myDate);
var newDate = cleanDate(data.myDate);
alert(newDate);
}
});
}
// bind myButton click event to call getData
$(document).ready(function() {
$('input#myButton').bind('click', getData);
});
</script>
我希望这个快速示例可以帮助其他与我遇到相同情况的人。目前,它似乎与 Microsoft JSON 序列化配合得很好,并且可以使我的日期跨时区保持正确。