Reputation: 4203
i have a strange situation. When i send a datetime value from view to controller with ajax, in controller the value is changed.
For example, if my view have a '30-08-2014' value (dd-MM-yyyy format), in my controller is received as '29-08-2014 23:00:00'.
I think the issue is in an invalid time zone, but both the browser and the application (controller) is running in my local computer, so they should have the same time zone
My current time zone is UTC-04:00 Santiago
This code generates the commented issue
Index 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>
Date 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);
}
}
Upvotes: 3
Views: 3391
Reputation: 1076
change this
$.ajax("Test/Date", {
data: myData,
dataType: 'HTML',
processData: true,
method: 'POST',
success: function(data) {
$('#result').html(data);
}
});
to
$.ajax("Test/Date", {
data: myData,
method: 'POST',
success: function(data) {
$('#result').html(data);
}
});
Updated
The issue as you see in the toISOString()
the value that is coming to the controller is the values showed in the javascript alert
.
Upvotes: 1
Reputation: 239430
You're sending the data converted to an ISO string. ISO is in UTC. The controller, then, interprets the date value in its own time zone (rather than UTC) because it doesn't know better. Long and short, don't use .toISOString()
. Especially, if all you care about is the date part, you're only going to shoot yourself in the foot passing around times as well. Just pass it formatted as YYYY-MM-DD.
Upvotes: 4