[英]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. 在Postman中,我通过POST将以下JSON发送到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. ...但是,出现以下错误: FormatException:无法将字符串识别为有效的DateTime。
Inside my controller, I'm using DateTimeFormat to format the date time: 在控制器内部,我正在使用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;
}
...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.
我的意图是格式化日期,因为它反映在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
). 您正在使用
'Z'
格式说明符和3位秒分数( fff
格式说明符 )来指定与UTC / Zulu日期时间完全相同'Z'
格式,但是crgStarteddatetime
中使用的值没有两者(即yyyy-MM-dd'T'HH:mm:ss
)。
Based on the JSON example, you should change the format to match exactly as provided in crgStarteddatetime
: 根据JSON示例,您应该更改格式以完全匹配
crgStarteddatetime
提供的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: 如果
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.