user20358
user20358

Reputation: 14766

Date format not maintained in jquery post

In my MVC 4 project developed in VS2010, I have a screen that has a dropdown that shows date as dd-MMM-yyyy for the display text, with the underlying value as dd-mm-yyyy.

In the function that posts the data, I can see that the selected value is in dd-mm-yyy when I alert it out.

  alert($("#dropdwn_BirthDateVal").val());

This line above shows my date as desired in dd-mm-yyyy format.

However in the same method when I try to post that value to my controller

  $.ajax({
            type: "POST",
            url:"@Url.Content("~/Home/GetUserDetails")",
            async:false,
            dataType: "JSON",
            data: {
                 //.....other string and integer values
                 //.....that go thru properly
                "myDto.DOB":  $("#dropdwn_BirthDateVal").val()
            },
            error: function (error) {
                alert(error);

           },

           ..... remaining code here 

...the date comes in as 1/1/0001 12:00:00 AM

The controller action I am posting to, 'GetUserDetails' has a ViewModel class called UserVM as its paramter. UserVM has a dto class called MyDto. Within MyDto is a Date property called DOB of type DateTime. MyDto has other properties as well. The string and integer values go thru properly.

What am I missing?

Upvotes: 0

Views: 1855

Answers (2)

sakura-bloom
sakura-bloom

Reputation: 4604

The DateTime received turns into 1/1/0001 12:00:00 AM because the date format (dd-mm-yyyy) could not be parsed properly. When the framework cannot parse your date/time string the result is what you have above.

The result depends on the localization of your machine. For example, under en-US localization, the .NET framework expects the date format to be in MM/dd/yyyy by default. But you can explicitly specify the format of the date as follows.

using System.Globalization;

// dateString is the string in your dd-MM-yyyy format
public void GetValidDate(string dateString) 
{
    DateTime parsedDateTime;
    DateTime.TryParseExact(dateString, "dd-MM-yyyy", null, 
                               DateTimeStyles.None, out parsedDateTime)
}

Look at the MSDN documentation.

Upvotes: 1

Jason
Jason

Reputation: 15931

You need to format the date as ISO-8601 when sending it to the server, e.g. 2011-12-19T15:28:46.493Z

This answer to this similiar question shows a number of way to accomplish this, my favorite is JSON.parse(JSON.stringify(new Date())) but that won't support IE7.

Upvotes: 5

Related Questions