设置 TimeSpan 格式以仅显示相关时间单位

Sup*_*JMN 1 .net c# timespan date

我的申请显示了预计完成时间 (ETA)。

我不想为用户提供完全格式化的TimeSpan,而是仅显示最相关的单元。用户不想看到0:00:39,766

例如,如果TimeSpan

  • 12天5小时42分15秒

我想将格式设置为“12 天”

如果TimeSpan

  • 5小时3分钟

它应该只显示“5 小时”,因为与分钟相比,小时数使得分钟数变得无关紧要。

几分钟都一样。15 分钟和 15 分 3 秒的格式应相同。

有没有标准化的方法来做到这一点?

Dmi*_*nko 5

没有标准方法,但您可以实现扩展方法

 public static partial class TimeSpanExtensions {
   public static string ToMyFormat(this TimeSpan ts) {
     return ts.Days != 0 ? $"{ts.Days} days"
          : ts.Hours != 0 ? $"{ts.Hours} hours"
          : ts.Minutes != 0 ? $"{ts.Minutes} minutes"
          : ts.Seconds != 0 ? $"{ts.Seconds} seconds"
          : $"{ts.Milliseconds} milliseconds";
   }
 }
Run Code Online (Sandbox Code Playgroud)

然后使用它:

 TimeSpan test = new TimeSpan(0, 415, 48, 44, 452);

 // 17 days (415 = 17 * 24 + 7 - 17 days 7 hours)
 Console.Write(ts.ToMyFormat());
Run Code Online (Sandbox Code Playgroud)