如何从 appsettings.json 获取日期时间?

Adm*_*and 6 c# datetime appsettings .net-core

我有 .net core 5.0 应用程序并尝试从 appsettings.json 获取 DateTime

应用程序设置.json:

"TimeModel": {
"RestartDuration": "27.10.2021 12:30:00"
 }
Run Code Online (Sandbox Code Playgroud)

代码:

 services.Configure<TimeModel>(
            configuration.GetSection("TimeModel"));
Run Code Online (Sandbox Code Playgroud)

错误:

 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.
Run Code Online (Sandbox Code Playgroud)

McK*_*bue 5

有几种方法可以做到这一点:

  1. 获取字符串形式的日期,然后解析它:DateTime.Parse(configuration.GetValue<string>("Date"))
  2. 您可以直接获取:configuration.GetValue<DateTime>("TimeModel")
  3. 您可以使用类模型。

在所有情况下,您都需要确保日期的格式为:默认2021-10-27T12:30:00