Skip to main content
 首页 » 编程设计

c#之如何将可为 null 的 TimeSpan 转换为具有特定格式的字符串

2024年02月13日21birdshome

我需要将 TimeSpan 转换为格式为 hh:mm tt 的字符串。

Timespan? tTime; 
Console.WriteLine(tTime.ToString("hh:mm tt")); 

ToString("hh:mm tt") 在值不为空时运行良好,但在值为空时会导致错误。

有什么解决办法吗?

请您参考如下方法:

出现错误的原因是 tTime.ToString("hh:mm tt") 试图强制将其值转换为具有所需格式的字符串。
如果该值为 null,则转换无法处理它,从而引发错误。

一种方法是按照@KevinCloet 的回答,他只是检查 tTime 是否有值,如果有则转换它。

//                validation     ? if true                          : if false 
Console.WriteLine(tTime.HasValue ? tTime.Value.ToString("hh:mm tt") : String.Empty); 

也可以写成:

// Boolean values don't need = true 
if(tTime.HasValue){ 
   Console.WriteLine(tTime.Value.ToString("hh:mm tt")); 
}else{ 
   Console.WriteLine(String.Empty); 
} 

另一种方法是通过 try{}catch(){} 方法,它与扩展的 if 语句几乎相同

try{ 
   Console.WriteLine(tTime.Value.ToString("hh:mm tt")); 
} 
catch(Exception e){ 
   // You don't actually need the 'Exception e',  
   // however 'e.Message' will tell you exactly what went wrong 
   Console.WriteLine(String.Empty); 
} 

我希望这个解释能帮助你理解,而不仅仅是给你一个答案。

编辑:
基于Jon Skeets answer on "" vs String.Empty ,您基本上可以使用任何一种。