このコード:
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 を返します。
[{"DateCreatedUtc":"2012-07-24T00:28:41.873877Z"},
{"DateCreatedUtc":"2012-07-24T00:28:41Z"}]
datetime から末尾のゼロが削除されたことに注意してください。しかし、これらの文字列を解析して DateTime を取得しようとすると、次のようになります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 Methodによると、これは正しいです:
FormatException
s には、format で指定されたパターンに対応する日時が含まれていません。
"o"
フォーマットは次のように定義されます。
yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK
明らかに末尾のゼロが存在する必要があります。
WebApi のバグですか、それとも何か間違っていますか? また、日付/時刻フィールドを .Net クライアントに渡すにはどうすればよいですか?
ありがとうございました。