2

I'm trying to get a TimeSpan from "24:30:00" string so I can define cacheOptions in C# but I'm getting 24 days instead of 24 hours.

string cacheExpirationTime = "24:00:00";
var cacheOptions = new MemoryCacheOptions()
{
    ExpirationScanFrequency = TimeSpan.Parse(cacheExpirationTime, CultureInfo.InvariantCulture)
};

I also tried without using CultureInfo, but it didn't work.

Which is the proper way to do this?

Aritzbn
  • 174
  • 3
  • 18

3 Answers3

2

24 hours is 1 day, so you should format it as such.

string cacheExpirationTime = "1.00:00:00";
var cacheOptions = new MemoryCacheOptions()
{
    ExpirationScanFrequency = TimeSpan.Parse(cacheExpirationTime, CultureInfo.InvariantCulture)
};
Mark Cilia Vincenti
  • 1,410
  • 8
  • 25
1

If you want to use the format hh:mm:ss. You need to specify the format, here "hh:mm:ss" is used. hh is for hours, mm for minutes, and ss for seconds.

Be aware that 24:00:00 could not be used because it's not a valid value for a TimeSpan object. The largest possible value for a TimeSpan object is 23:59:59, so any value greater than that will cause an OverflowException to be thrown.

string cacheExpirationTime = "23:59:59";
string format = "hh\\:mm\\:ss";

var cacheOptions = new MemoryCacheOptions()
{
    ExpirationScanFrequency = TimeSpan.ParseExact(cacheExpirationTime, format, CultureInfo.InvariantCulture)
};
Filip Huhta
  • 2,043
  • 7
  • 25
0

By default, TimeStamp assumes the input string represents a time duration in the format days.hours:minutes:seconds so you need to use a custom format string with TimeSpan.ParseExact() method like this:

string cacheExpirationTime = "24:00:00";
var cacheOptions = new MemoryCacheOptions()
{
    ExpirationScanFrequency = TimeSpan.ParseExact(cacheExpirationTime, @"h\:mm\:ss", CultureInfo.InvariantCulture)
};
Doma G2
  • 34
  • 3