Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get DateTime from appsettings.json?

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.
like image 502
Admiral Land Avatar asked Jul 31 '26 00:07

Admiral Land


1 Answers

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.

like image 115
McKabue Avatar answered Aug 06 '26 13:08

McKabue



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!