如何从 appsettings.json 获取日期时间?
How to get DateTime from appsettings.json?
我有 .net core 5.0 应用程序并尝试从 appsettings.json
获取 DateTime
appsettings.json:
"TimeModel": {
"RestartDuration": "27.10.2021 12:30:00"
}
代码:
services.Configure<TimeModel>(
configuration.GetSection("TimeModel"));
错误:
System.InvalidOperationException: Failed to convert configuration value at 'TimeModel:RestartDuration' to type 'System.DateTime'.
---> System.FormatException: 27.10.2021 12:30:00 is not a valid value for DateTime.
---> System.FormatException: String '27.10.2021 12:30:00' was not recognized as a valid DateTime.
您可以通过多种方式完成此操作:
- 获取字符串形式的日期,然后对其进行解析:
DateTime.Parse(configuration.GetValue<string>("Date"))
- 可以直接得到:
configuration.GetValue<DateTime>("TimeModel")
- 您可以使用 class 模型。
在所有情况下,您都需要确保日期的格式为:默认为 2021-10-27T12:30:00
。
我有 .net core 5.0 应用程序并尝试从 appsettings.json
获取 DateTimeappsettings.json:
"TimeModel": {
"RestartDuration": "27.10.2021 12:30:00"
}
代码:
services.Configure<TimeModel>(
configuration.GetSection("TimeModel"));
错误:
System.InvalidOperationException: Failed to convert configuration value at 'TimeModel:RestartDuration' to type 'System.DateTime'.
---> System.FormatException: 27.10.2021 12:30:00 is not a valid value for DateTime.
---> System.FormatException: String '27.10.2021 12:30:00' was not recognized as a valid DateTime.
您可以通过多种方式完成此操作:
- 获取字符串形式的日期,然后对其进行解析:
DateTime.Parse(configuration.GetValue<string>("Date"))
- 可以直接得到:
configuration.GetValue<DateTime>("TimeModel")
- 您可以使用 class 模型。
在所有情况下,您都需要确保日期的格式为:默认为 2021-10-27T12:30:00
。