Vladimir Venegas Vladimir Venegas - 1 year ago 101
JSON Question

date is changing when is sent to controller with ajax

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 = "";

<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 () {
var myData = { myDate: $('#my-date').val().toDate().toISOString() };
$.ajax("Test/Date", {
data: myData,
dataType: 'HTML',
processData: true,
method: 'POST',
success: function(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]);
<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">


Date View

@model DateTime
Layout = "";

@string.Format("Input date is {0}", Model.ToString("dd-MM-yyyy HH:mm:ss.fff tt"))


public class TestController : Controller
public ActionResult Index()
return View();

public ActionResult Date(DateTime myDate)
return PartialView(myDate);

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download