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

后端 未结 19 1274
情深已故
情深已故 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:52

    This is the approach I used my self with conditional formatting. and I post it here because I think this is clean way.

    $"{time.Days:#0:;;\\}{time.Hours:#0:;;\\}{time.Minutes:00:}{time.Seconds:00}"
    

    example of outputs:

    00:00 (minimum)

    1:43:04 (when we have hours)

    15:03:01 (when hours are more than 1 digit)

    2:4:22:04 (when we have days.)

    The formatting is easy. time.Days:#0:;;\\ the format before ;; is for when value is positive. negative values are ignored. and for zero values we have;;\\ in order to hide it in formatted string. note that the escaped backslash is necessary otherwise it will not format correctly.

    0 讨论(0)
  • 2020-11-22 12:56

    One way is to create a DateTime object and use it for formatting:

    new DateTime(myTimeSpan.Ticks).ToString(myCustomFormat)
    
    // or using String.Format:
    String.Format("{0:HHmmss}", new DateTime(myTimeSpan.Ticks))
    

    This is the way I know. I hope someone can suggest a better way.

    0 讨论(0)
  • 2020-11-22 12:56

    I used the code below. It is long, but still it is one expression, and produces very friendly output, as it does not outputs days, hours, minutes, or seconds if they have value of zero.

    In the sample it produces output: "4 days 1 hour 3 seconds".

    TimeSpan sp = new TimeSpan(4,1,0,3);
    string.Format("{0}{1}{2}{3}", 
            sp.Days > 0 ? ( sp.Days > 1 ? sp.ToString(@"d\ \d\a\y\s\ "): sp.ToString(@"d\ \d\a\y\ ")):string.Empty,
            sp.Hours > 0 ? (sp.Hours > 1 ? sp.ToString(@"h\ \h\o\u\r\s\ ") : sp.ToString(@"h\ \h\o\u\r\ ")):string.Empty,
            sp.Minutes > 0 ? (sp.Minutes > 1 ? sp.ToString(@"m\ \m\i\n\u\t\e\s\ ") :sp.ToString(@"m\ \m\i\n\u\t\e\ ")):string.Empty,
            sp.Seconds > 0 ? (sp.Seconds > 1 ? sp.ToString(@"s\ \s\e\c\o\n\d\s"): sp.ToString(@"s\ \s\e\c\o\n\d\s")):string.Empty);
    
    0 讨论(0)
  • 2020-11-22 12:56

    This is a pain in VS 2010, here's my workaround solution.

     public string DurationString
            {
                get 
                {
                    if (this.Duration.TotalHours < 24)
                        return new DateTime(this.Duration.Ticks).ToString("HH:mm");
                    else //If duration is more than 24 hours
                    {
                        double totalminutes = this.Duration.TotalMinutes;
                        double hours = totalminutes / 60;
                        double minutes = this.Duration.TotalMinutes - (Math.Floor(hours) * 60);
                        string result = string.Format("{0}:{1}", Math.Floor(hours).ToString("00"), Math.Floor(minutes).ToString("00"));
                        return result;
                    }
                } 
            }
    
    0 讨论(0)
  • 2020-11-22 12:59

    Simple. Use TimeSpan.ToString with c, g or G. More information at MSDN

    0 讨论(0)
  • 2020-11-22 12:59

    You can also go with:

    Dim ts As New TimeSpan(35, 21, 59, 59)  '(11, 22, 30, 30)    '
    Dim TimeStr1 As String = String.Format("{0:c}", ts)
    Dim TimeStr2 As String = New Date(ts.Ticks).ToString("dd.HH:mm:ss")
    

    EDIT:

    You can also look at Strings.Format.

        Dim ts As New TimeSpan(23, 30, 59)
        Dim str As String = Strings.Format(New DateTime(ts.Ticks), "H:mm:ss")
    
    0 讨论(0)
提交回复
热议问题