Reputation: 11227
This 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(),
},
};
}
returns the following JSON:
[{"DateCreatedUtc":"2012-07-24T00:28:41.873877Z"},
{"DateCreatedUtc":"2012-07-24T00:28:41Z"}]
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);
which is correct, according to MSDN DateTime.ParseExact Method:
FormatException
s does not contain a date and time that corresponds to the pattern specified in format.
and "o"
format is defined as follows:
yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK
so clearly trailing zeros SHOULD be there.
Is it a bug in WebApi, or am I doing something wrong? And how should I pass date/time field to my .Net client?
Thank you.
Upvotes: 2
Views: 8935
Reputation: 1500585
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.
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);
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.
Upvotes: 5