简体   繁体   中英

ASP.NET Controller FormatException: String was not recognized as a valid DateTime

In Postman, I'm sending the following JSON via a POST to API.

{
"id": "21",
"crgName": "Walgreens - 11/07/2018 - Standard ",
"crgStarteddatetime": "2018-11-07T10:11:10",
}

...but, I get the following error: FormatException: String was not recognized as a valid DateTime.

Inside my controller, I'm using DateTimeFormat to format the date time:

 public static RemoteContextType DeserializeJsonString<RemoteContextType>(string jsonString)
        {
            //create an instance of generic type object
            RemoteContextType obj = Activator.CreateInstance<RemoteContextType>();
            MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString));

            var serializer = new DataContractJsonSerializer(obj.GetType(),
                new DataContractJsonSerializerSettings
                {
                    DateTimeFormat = new

                             DateTimeFormat("yyyy-MM-dd'T'HH:mm:ss.fff'Z'")
                });

            obj = (RemoteContextType)serializer.ReadObject(ms);

            ms.Close();

            return obj;
           }

...is there an issue in my syntax as to how I have the Date formatted? My intentions are to formate the date as it is reflected in the JSON. Could I get some help as to what am I doing wrong?

The problem lies in this line:

DateTimeFormat = new DateTimeFormat("yyyy-MM-dd'T'HH:mm:ss.fff'Z'")

You're specifying the format exactly as UTC/Zulu datetime with 'Z' format specifier and 3 digits of seconds fraction ( fff format specifier ), but the value used in crgStarteddatetime doesn't have both of them (ie yyyy-MM-dd'T'HH:mm:ss ).

Based on the JSON example, you should change the format to match exactly as provided in crgStarteddatetime :

var serializer = new DataContractJsonSerializer(obj.GetType(), new DataContractJsonSerializerSettings
                 {
                     DateTimeFormat = new DateTimeFormat("yyyy-MM-dd'T'HH:mm:ss")
                 });

If actual JSON data of crgStarteddatetime has mixed date formats (some of the dates have yyyy-MM-dd'T'HH:mm:ss and others may have yyyy-MM-dd'T'HH:mm:ss'Z' ), use K format specifier which is more flexible to handle timezone format:

var serializer = new DataContractJsonSerializer(obj.GetType(), new DataContractJsonSerializerSettings
                 {
                     DateTimeFormat = new DateTimeFormat("yyyy-MM-dd'T'HH:mm:ssK")
                 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM