问题描述
这code:
public class PhotoDescriptor
{
public DateTime DateCreatedUtc { get; set; }
}
public class PhotosController : ApiController
{
// GET api/photos
public IEnumerable<PhotoDescriptor> GetListOfPhotos()
{
return new PhotoDescriptor[]
{
new PhotoDescriptor
{
DateCreatedUtc = DateTime.ParseExact(
"2012-07-24T00:28:41.8738770Z",
"o",
CultureInfo.InvariantCulture,
DateTimeStyles.None).ToUniversalTime(),
},
new PhotoDescriptor
{
DateCreatedUtc = DateTime.ParseExact(
"2012-07-24T00:28:41.0000000Z",
"o",
CultureInfo.InvariantCulture,
DateTimeStyles.None).ToUniversalTime(),
},
};
}
返回以下JSON:
returns the following JSON:
[{"DateCreatedUtc":"2012-07-24T00:28:41.873877Z"},
{"DateCreatedUtc":"2012-07-24T00:28:41Z"}]
通知,尾随零是从日期时间删除。但是,当我试图解析这些字符串,让我的日期时间回来,我得到出现FormatException - 字符串未被识别为有效的DateTime
:
notice that trailing zeros were removed from the datetime. But when I'm trying to parse these strings to get my DateTime back, I get FormatException - String was not recognized as a valid DateTime
:
var date = DateTime.ParseExact("2012-07-24T00:28:41.873877Z", "o", CultureInfo.InvariantCulture, DateTimeStyles.None);
这是正确的,根据MSDN DateTime.ParseExact方法:
出现FormatException 的
s不包含对应于日期和时间 该模式指定的格式。
s does not contain a date and time that corresponds to the pattern specified in format.
和O
格式的如下:
YYYY' - 'MM' - 'dd'T'HH:毫米:SS fffffffK
这么清楚尾随零应该在那里。
so clearly trailing zeros SHOULD be there.
时它的WebAPI一个bug,还是我做错了什么?而且我应该怎么传递的日期/时间字段,以我的.Net客户端?
Is it a bug in WebApi, or am I doing something wrong? And how should I pass date/time field to my .Net client?
感谢你。
推荐答案
是的,你是正确解析硬codeD值 - 但你的code显示一无所知,他们应该怎么写出来的JSON 。你的应该的主张只是相对于你的格式的解析的的,这当然不是在传播的的DateTime
本身
Yes, you're parsing the hard-coded values appropriately - but your code shows nothing about how they should be written out in JSON. Your "should be" claim is only with respect to the format you're parsing in, which of course isn't propagated within the DateTime
itself.
如果要分析自己的价值(我不得不问为什么不是正在为你做......),你可以使用 F
而不是 F
:
If you want to parse the values yourself (and I have to ask why that's not being done for you...) you can use F
instead of f
:
DateTime value = DateTime.ParseExact(text,
"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'FFFFFFFK",
CultureInfo.InvariantCulture);
我并不是说它的不是的中的WebAPI的错误 - 但我还没有看到任何迹象表明它的是的从你的文章中的WebAPI的错误。 ..和斯科特Hanselman的约会中的WebAPI帖子举例说明这是刚下到第二,这表明是故意的。
I'm not saying it isn't a bug in WebApi - but I haven't seen any indication that it is a bug in WebApi from your post... and Scott Hanselman's post on dates in WebApi give examples which are "just down to the second", suggesting that's deliberate.
这篇关于的WebAPI序列化的DateTime - 如何反序列化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!