簡體   English   中英

ASP.NET控制器FormatException:字符串未被識別為有效的DateTime

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

在Postman中,我通過POST將以下JSON發送到API。

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

...但是,出現以下錯誤: FormatException:無法將字符串識別為有效的DateTime。

在控制器內部,我正在使用DateTimeFormat格式化日期時間:

 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;
           }

...我的語法中是否有關於日期格式的問題? 我的意圖是格式化日期,因為它反映在JSON中。 我做錯了什么可以幫助我嗎?

問題出在這一行:

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

您正在使用'Z'格式說明符和3位秒分數( fff格式說明符 )來指定與UTC / Zulu日期時間完全相同'Z'格式,但是crgStarteddatetime中使用的值沒有兩者(即yyyy-MM-dd'T'HH:mm:ss )。

根據JSON示例,您應該更改格式以完全匹配crgStarteddatetime提供的crgStarteddatetime

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

如果crgStarteddatetime實際JSON數據具有混合的日期格式(某些日期具有yyyy-MM-dd'T'HH:mm:ss而其他日期則具有yyyy-MM-dd'T'HH:mm:ss'Z' ) ,請使用K格式說明符 ,它更靈活地處理時區格式:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM