How to get DateTime from appsettings.json?
Asked Answered
B

1

6

I have .net core 5.0 application and try to get DateTime from appsettings.json

appsettings.json:

"TimeModel": {
"RestartDuration": "27.10.2021 12:30:00"
 }

Code:

 services.Configure<TimeModel>(
            configuration.GetSection("TimeModel"));

Error:

 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.
Biforked answered 27/10, 2021 at 10:16 Comment(3)
Start by storing your string representation of a DateTime in your AppSettings.json as ISO8601 - "27.10.2021T12:30:00"Guilbert
@ZoharPeled dotnetfiddle also threw on that one. "2021-10-27T12:30:00" worked. Or ParseExact: dotnetfiddle.net/do45kiRadiation
@Radiation Of course you're correct. I don't know how I've missed it.Guilbert
S
5

There are several ways you could do it:

  1. Get the date as a string, then parse it: DateTime.Parse(configuration.GetValue<string>("Date"))
  2. You can get directly: configuration.GetValue<DateTime>("TimeModel")
  3. You can use a class model.

In all cases, you need to make sure the date is in the format: 2021-10-27T12:30:00 by default.

Shenashenan answered 27/10, 2021 at 15:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.