0

I am posting JSON Data to my controller. One of the fields contains date. When i send date in MM/dd/yyyy format, the controller is taking dd/MM/yyyy format. Due to this my month is becoming day at server side. If i send 3/20/2017 then it is becoming 01/01/0001 at server side because 20 is not a valid month. How do i force controller to take 3/20/2017 in MM/dd/yyyy format. I initially though iis is referring my system time format. But it did not work even after i changed my system date format to MM/dd/yyyy.

Sample JSON which i am sending to server. Request type is POST. (Here i am posting only date field but in my actual request i have other fields too.)

{date:"3/20/2017"}

Model:

Test{
public DateTime Date{get;set;}
}

Action:

ActionResult Demo(Test test)
{
//some code
}

1 Answers1

1

Suppose you have this AJAX call:

var date = "3/20/2017";
...
$.ajax({
        ...
        url: '/Controller/Demo',
        type: 'POST',
        data: { date: date },
        dataType: 'json',
        ...
       });

In controller side, use DateTime.ParseExact to convert date into DateTime format:

[HttpPost]
public ActionResult Demo(String date)
{
    // other stuff
    ...
    var test = new Test();
    test.Date = DateTime.ParseExact(date, "M/d/yyyy", CultureInfo.InvariantCulture);
    ...
    // other stuff
}

To prevent hassles with date formatting, conversion to UTC with toISOString() method is more recommended (see /a/23502790 for details):

View (JS)

var date = new Date("3/20/2017").toISOString();

Controller

test.Date = DateTime.Parse(date);
Community
  • 1
  • 1
Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61