TL;DR: I would like the result of binding DateTime values from IConfiguration to be the same as DateTime.Parse(stringValue, null, DateTimeStyles.RoundtripKind), but by default it is the same as DateTime.Parse(stringValue).
I'm using the binding functionality of IConfiguration to pull DateTime values out of configuration.
Say I have a JSON configuration that looks like this:
{
testValue: "2020-03-08T14:37:46.9793888Z"
}
I might pull the value out as a DateTime in one of a few ways. Here are the first two I thought of:
// Directly from IConfiguration
var dateTimeValue = configuration.GetValue<DateTime>("testValue");
// By configuring options
// Assuming this class exists
private class TestOptions
{
public DateTime TestValue { get; set; }
}
// Set up options on a service provider
var services = new ServiceCollection();
services.Configure<TestOptions>(configuration);
var provider = services.BuildServiceProvider();
// Get as a service
var options = provider.GetRequiredService<IOptions<TestOptions>>().Value;
return options.TestValue;
The result of doing these, at least by default, is more or less equivalent to applying an ordinary parse:
// Bad, ignores Kind
var dateTimeValue = DateTime.Parse(stringValue)
I'm working on code that pays attention to the Kind property of the DateTime. The ordinary parse ignores "Z" times and makes anything with a time zone indication Local. An invocation like this, with the RoundtripKind style, fixes the problem:
// Good, uses Kind if available
var dateTimeValue = DateTime.Parse(stringValue, null, DateTimeStyles.RoundtripKind);
Is there any way to force the configuration binder to use this invocation instead of the default?