我有一个奇怪的情况。当我使用 ajax 将日期时间值从 View 发送到 Controller 时,在 Controller 中该值被更改。
例如,如果我的 View 有一个“30-08-2014”值(dd-MM-yyyy 格式),在我的 Controller 中收到的是“29-08-2014 23:00:00”。
我认为问题是在无效的时区,但浏览器和应用程序( Controller )都在我的本地计算机上运行,所以它们应该具有相同的时区
我当前的时区是 UTC-04:00 圣地亚哥
此代码生成评论问题
索引 View
@{
Layout = "";
}
<html>
<head>
<script src="@Url.Content("~/Content/Plugins/jQuery/jquery-1.11.3.min.js")"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$('#send-date').on('click', function () {
$('#value-from-user').val($('#my-date').val().toDate().toISOString());
var myData = { myDate: $('#my-date').val().toDate().toISOString() };
$.ajax("Test/Date", {
data: myData,
dataType: 'HTML',
processData: true,
method: 'POST',
success: function(data) {
$('#result').html(data);
}
});
});
});
//input is dd-MM-yyyy format
String.prototype.toDate = function () {
var parts = this.split("-");
return new Date(parts[2], parts[1] - 1, parts[0]);
}
</script>
</head>
<body>
<input type="text" id="value-from-user" disabled/> <br />
<label for="my-date">Input in dd-MM-yyyy format</label><input type="text" name="my-date" id="my-date" value="30-08-2014"/> <br/>
<input type="button" name="send-date" id="send-date" value="Send Date"/><br/>
<div id="result">
</div>
</body>
</html>
日期 View
@model DateTime
@{
Layout = "";
}
@string.Format("Input date is {0}", Model.ToString("dd-MM-yyyy HH:mm:ss.fff tt"))
Controller
public class TestController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Date(DateTime myDate)
{
return PartialView(myDate);
}
}
最佳答案
您正在发送转换为 ISO 字符串的数据。 ISO 在 UTC 中。然后, Controller 在其自己的时区(而不是 UTC)中解释日期值,因为它不知道更好。总之,不要使用 .toISOString()
。特别是,如果您只关心日期部分,那么您也只会搬起石头砸自己的脚。只需将其格式设置为 YYYY-MM-DD 即可。
关于c# - 当使用 ajax 发送到 Controller 时,日期正在改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37949627/