简体   繁体   English

Json到DateTime-更改格式

[英]Json to DateTime - change format

I send from JS (with JSON) to server (C#) a string date in format "dd/mm/yyyy" - for example "23/10/2014", but C# DateTime gets null. 我从JS(带有JSON)向服务器(C#)发送了一个字符串日期,格式为“ dd / mm / yyyy”,例如“ 23/10/2014”,但C#DateTime为空。 If I send "10/23/2014" it works. 如果我发送“ 10/23/2014”,则可以正常运行。 I use MVC4. 我使用MVC4。

How can I change that format that DateTime gets to I'll be able to send "23/10/2014"? 如何更改DateTime可以发送的格式“ 23/10/2014”?

Not a direct answer to your question but I think you're safer to send the date as: yyyy/mm/dd 这不是您问题的直接答案,但我认为将日期发送为: yyyy / mm / dd更安全

Then you don't need to worry about internationalisation. 然后,您不必担心国际化。 MVC will parse this correctly. MVC将正确解析此。

EDIT 编辑

Matt made a good comment below. 马特在下面发表了很好的评论。 The format of the date should be: yyyy-mm-dd which is in agreement with the ISO 8601 standard. 日期格式应为: yyyy-mm-dd ,它与ISO 8601标准一致。

you can specify the date format in the serialization settings 您可以在序列化设置中指定日期格式

var jsonString = @"{'ID':'1','Date':'23/10/2014'}";

JsonSerializerSettings jSettings = new Newtonsoft.Json.JsonSerializerSettings()
{
    DateFormatString = "dd/MM/yyyy"
};

var result = JsonConvert.DeserializeObject<TheType>(jsonString, jSettings);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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