簡體   English   中英

從 HH:mm:ss 字符串獲取 TimeSpan

[英]Get TimeSpan from HH:mm:ss string

我正在嘗試從"24:30:00"字符串獲取TimeSpan ,以便我可以在 C# 中定義 cacheOptions,但我得到的是 24 天而不是 24 小時。

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

我也嘗試過不使用CultureInfo ,但它沒有用。

執行此操作的正確方法是什么?

24 小時是 1 天,所以你應該這樣格式化。

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

如果你想使用格式hh:mm:ss 您需要指定格式,此處使用“ hh:mm:ss ”。 hh 代表小時,mm 代表分鍾,ss 代表秒。

請注意,無法使用24:00:00 ,因為它不是TimeSpan object 的有效值。TimeSpan object 的最大可能值為23:59:59 ,因此任何大於該值的值都會導致OverflowException拋出。

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

var cacheOptions = new MemoryCacheOptions()
{
    ExpirationScanFrequency = TimeSpan.ParseExact(cacheExpirationTime, format, CultureInfo.InvariantCulture)
};

默認情況下, TimeStamp假定輸入字符串表示格式days.hours:minutes:seconds的持續時間,因此您需要使用帶有TimeSpan.ParseExact()方法的自定義格式字符串,如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM