How to get Web API OData v4 to use DateTime
So far, DateTime is not the part of the OASIS OData V4 standard and Web API doesn't support the DateTime type while it do support the DateTimeOffset type.
However, OData Team are working on supporting the DataTime type now. I'd expect you can use the DateTime type in the next Web API release. If you can't wait for the next release, I wrote an example based on the blog . Hope it can help you. Thanks.
Model
public class Customer
{
private DateTimeWrapper dtw;
public int Id { get; set; }
public string Name { get; set; }
public DateTime Birthday
{
get { return dtw; }
set { dtw = value; }
}
[NotMapped]
public DateTimeOffset BirthdayOffset
{
get { return dtw; }
set { dtw = value; }
}
}
public class DateTimeWrapper
{
public static implicit operator DateTimeOffset(DateTimeWrapper p)
{
return DateTime.SpecifyKind(p._dt, DateTimeKind.Utc);
}
public static implicit operator DateTimeWrapper(DateTimeOffset dto)
{
return new DateTimeWrapper(dto.DateTime);
}
public static implicit operator DateTime(DateTimeWrapper dtr)
{
return dtr._dt;
}
public static implicit operator DateTimeWrapper(DateTime dt)
{
return new DateTimeWrapper(dt);
}
protected DateTimeWrapper(DateTime dt)
{
_dt = dt;
}
private readonly DateTime _dt;
}
DB Context
public DbSet<Customer> Customers { get; set; }
EdmModel
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Customer>("Customers");
var cu = builder.StructuralTypes.First(t => t.ClrType == typeof(Customer));
cu.AddProperty(typeof(Customer).GetProperty("BirthdayOffset"));
var customer = builder.EntityType<Customer>();
customer.Ignore(t => t.Birthday);
var model = builder.GetEdmModel();
config.MapODataServiceRoute("odata", "odata", model);
Controller
Add the OData Controller as normal.
Test
Payload
Finally Web API OData v4 now supports DateTime
type in release 5.5 . Get latest nuget package and don't forget setting this:
config.SetTimeZoneInfo(TimeZoneInfo.Utc);
otherwise the timezone of the dateTime property would be considered as local timezone.
More info: ASP.NET Web API for OData V4 Docs DateTime support