How can I String.Format a TimeSpan object with a custom format in .NET?

后端 未结 19 1573
情深已故
情深已故 2020-11-22 12:25

What is the recommended way of formatting TimeSpan objects into a string with a custom format?

19条回答
  •  天命终不由人
    2020-11-22 12:36

    I wanted to return a string such as "1 day 2 hours 3 minutes" and also take into account if for example days or minuttes are 0 and then not showing them. thanks to John Rasch for his answer which mine is barely an extension of

    TimeSpan timeLeft = New Timespan(0, 70, 0);
    String.Format("{0}{1}{2}{3}{4}{5}",
        Math.Floor(timeLeft.TotalDays) == 0 ? "" : 
        Math.Floor(timeLeft.TotalDays).ToString() + " ",
        Math.Floor(timeLeft.TotalDays) == 0 ? "" : Math.Floor(timeLeft.TotalDays) == 1 ? "day " : "days ",
        timeLeft.Hours == 0 ? "" : timeLeft.Hours.ToString() + " ",
        timeLeft.Hours == 0 ? "" : timeLeft.Hours == 1 ? "hour " : "hours ",
        timeLeft.Minutes == 0 ? "" : timeLeft.Minutes.ToString() + " ",
        timeLeft.Minutes == 0 ? "" : timeLeft.Minutes == 1 ? "minute " : "minutes ");
    

提交回复
热议问题