代码之家  ›  专栏  ›  技术社区  ›  Hosam Aly

如何在.NET中使用自定义格式对TimeSpan对象进行字符串格式化?

  •  171
  • Hosam Aly  · 技术社区  · 16 年前

    推荐的格式化方式是什么 TimeSpan

    19 回复  |  直到 5 年前
        1
  •  259
  •   Community pid    7 年前

    JohannesH's answer .

    在.Net 4.0中引入了自定义TimeSpan格式字符串。您可以在MSDN上找到可用格式说明符的完整参考 Custom TimeSpan Format Strings

    以下是timespan格式字符串的示例:

    string.Format("{0:hh\\:mm\\:ss}", myTimeSpan); //example output 15:36:15
    

    ( 使现代化 )下面是一个使用C#6字符串插值的示例:

    $"{myTimeSpan:hh\\:mm\\:ss}"; //example output 15:36:15
    

    需要用“\”转义“:”字符(除非使用逐字字符串,否则必须转义“\”字符本身)。

    这是MSDN的摘录 页面说明如何转义格式字符串中的“:”和“.”字符:

        2
  •  93
  •   Community pid    7 年前

    string.Format ("{0:00}:{1:00}:{2:00}", 
                   (int)myTimeSpan.TotalHours, 
                        myTimeSpan.Minutes, 
                        myTimeSpan.Seconds);
    

    answer 关于字节

    有关.NET 4.0及更高版本的信息,请参见DoctaJonez answer

        3
  •  31
  •   Hosam Aly    16 年前

    一种方法是创建一个 DateTime 对象并将其用于格式化:

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

        4
  •  10
  •   MrMaavin    5 年前

    易于理解的使用 TimeSpan.ToString MSDN

        5
  •  8
  •   Shehab Fawzy    9 年前

    我会和你一起去

    myTimeSpan.ToString("hh\\:mm\\:ss");
    
        6
  •  6
  •   Martijn Pieters    12 年前
    Dim duration As New TimeSpan(1, 12, 23, 62)
    
    DEBUG.WriteLine("Time of Travel: " + duration.ToString("dd\.hh\:mm\:ss"))
    

    http://msdn.microsoft.com/en-us/library/ee372287.aspx

        7
  •  6
  •   NoOne    11 年前

    TimeSpan ts = ...;
    string.Format("{0:%d}d {0:%h}h {0:%m}m {0:%s}s", ts);
    

    string.Format("{0:%d}days {0:%h}hours {0:%m}min {0:%s}sec", ts);
    string.Format("{0:%d}d {0:%h}h {0:%m}' {0:%s}''", ts);
    
        8
  •  5
  •   sc911    9 年前

    这真是太棒了:

    string.Format("{0:00}:{1:00}:{2:00}",
                   (int)myTimeSpan.TotalHours,
                   myTimeSpan.Minutes,
                   myTimeSpan.Seconds);
    
        9
  •  3
  •   NeverHopeless    12 年前

    您还可以选择:

    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")
    

    编辑:

    你也可以看看 Strings.Format .

        Dim ts As New TimeSpan(23, 30, 59)
        Dim str As String = Strings.Format(New DateTime(ts.Ticks), "H:mm:ss")
    
        10
  •  3
  •   Ryan Williams    8 年前
    if (timeSpan.TotalDays < 1)
        return timeSpan.ToString(@"hh\:mm\:ss");
    
    return timeSpan.TotalDays < 2
        ? timeSpan.ToString(@"d\ \d\a\y\ hh\:mm\:ss")
        : timeSpan.ToString(@"d\ \d\a\y\s\ hh\:mm\:ss");
    

    所有文字字符都必须转义。

        11
  •  2
  •   Community pid    4 年前

    这是我自己使用的条件格式的方法。我把它贴在这里,因为我认为这是一种干净的方式。

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

    输出示例:

    00:00 (最低限度)

    1:43:04 (当我们有时间的时候)

    15:03:01

    2:4:22:04 (当我们有天的时候。)

    格式化很容易。 time.Days:#0:;;\\ 以前的格式 ;; 用于值为正值时。负值被忽略。对于零值,我们有 ;;\\ 以便将其隐藏在格式化字符串中。请注意,转义的反斜杠是必需的,否则将无法正确格式化。

        12
  •  2
  •   chviLadislav    7 年前

    这是我的 extension method :

    public static string ToFormattedString(this TimeSpan ts)
    {
        const string separator = ", ";
    
        if (ts.TotalMilliseconds < 1) { return "No time"; }
    
        return string.Join(separator, new string[]
        {
            ts.Days > 0 ? ts.Days + (ts.Days > 1 ? " days" : " day") : null,
            ts.Hours > 0 ? ts.Hours + (ts.Hours > 1 ? " hours" : " hour") : null,
            ts.Minutes > 0 ? ts.Minutes + (ts.Minutes > 1 ? " minutes" : " minute") : null,
            ts.Seconds > 0 ? ts.Seconds + (ts.Seconds > 1 ? " seconds" : " second") : null,
            ts.Milliseconds > 0 ? ts.Milliseconds + (ts.Milliseconds > 1 ? " milliseconds" : " millisecond") : null,
        }.Where(t => t != null));
    }
    

    示例调用:

    string time = new TimeSpan(3, 14, 15, 0, 65).ToFormattedString();
    

    3 days, 14 hours, 15 minutes, 65 milliseconds
    
        13
  •  1
  •   panpawel    10 年前

    我使用了下面的代码。它很长,但仍然是一个表达式,并产生非常友好的输出,因为如果天、小时、分钟或秒的值为零,它不会输出天、小时、分钟或秒。

    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);
    
        14
  •  1
  •   Dabriel    10 年前

    我用这个方法。我是比利时人,会说荷兰语,所以小时和分钟的复数形式不仅仅是在结尾加上“s”,而是和单数几乎不同的词。

    它可能看起来很长,但我认为它可读性很强:

     public static string SpanToReadableTime(TimeSpan span)
        {
            string[] values = new string[4];  //4 slots: days, hours, minutes, seconds
            StringBuilder readableTime = new StringBuilder();
    
            if (span.Days > 0)
            {
                if (span.Days == 1)
                    values[0] = span.Days.ToString() + " dag"; //day
                else
                    values[0] = span.Days.ToString() + " dagen";  //days
    
                readableTime.Append(values[0]);
                readableTime.Append(", ");
            }
            else
                values[0] = String.Empty;
    
    
            if (span.Hours > 0)
            {
                if (span.Hours == 1)
                    values[1] = span.Hours.ToString() + " uur";  //hour
                else
                    values[1] = span.Hours.ToString() + " uren";  //hours
    
                readableTime.Append(values[1]);
                readableTime.Append(", ");
    
            }
            else
                values[1] = string.Empty;
    
            if (span.Minutes > 0)
            {
                if (span.Minutes == 1)
                    values[2] = span.Minutes.ToString() + " minuut";  //minute
                else
                    values[2] = span.Minutes.ToString() + " minuten";  //minutes
    
                readableTime.Append(values[2]);
                readableTime.Append(", ");
            }
            else
                values[2] = string.Empty;
    
            if (span.Seconds > 0)
            {
                if (span.Seconds == 1)
                    values[3] = span.Seconds.ToString() + " seconde";  //second
                else
                    values[3] = span.Seconds.ToString() + " seconden";  //seconds
    
                readableTime.Append(values[3]);
            }
            else
                values[3] = string.Empty;
    
    
            return readableTime.ToString();
        }//end SpanToReadableTime
    
        15
  •  1
  •   Ken Y-N    7 年前

     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;
                    }
                } 
            }
    
        16
  •  1
  •   GER    6 年前

    这个 Substring 当您只需要小时:分钟:秒时,该方法可以完美地工作。它的代码简单明了,易于理解。

        var yourTimeSpan = DateTime.Now - DateTime.Now.AddMinutes(-2);
    
        var formatted = yourTimeSpan.ToString().Substring(0,8);// 00:00:00 
    
        Console.WriteLine(formatted);
    
        17
  •  0
  •   JHo    8 年前

    这是我的版本。它只显示必要的内容,处理多元化、负片,我试着让它变得轻量级。

    输出示例

    0 seconds
    1.404 seconds
    1 hour, 14.4 seconds
    14 hours, 57 minutes, 22.473 seconds
    1 day, 14 hours, 57 minutes, 22.475 seconds
    

    public static class TimeSpanExtensions
    {
        public static string ToReadableString(this TimeSpan timeSpan)
        {
            int days = (int)(timeSpan.Ticks / TimeSpan.TicksPerDay);
            long subDayTicks = timeSpan.Ticks % TimeSpan.TicksPerDay;
    
            bool isNegative = false;
            if (timeSpan.Ticks < 0L)
            {
                isNegative = true;
                days = -days;
                subDayTicks = -subDayTicks;
            }
    
            int hours = (int)((subDayTicks / TimeSpan.TicksPerHour) % 24L);
            int minutes = (int)((subDayTicks / TimeSpan.TicksPerMinute) % 60L);
            int seconds = (int)((subDayTicks / TimeSpan.TicksPerSecond) % 60L);
            int subSecondTicks = (int)(subDayTicks % TimeSpan.TicksPerSecond);
            double fractionalSeconds = (double)subSecondTicks / TimeSpan.TicksPerSecond;
    
            var parts = new List<string>(4);
    
            if (days > 0)
                parts.Add(string.Format("{0} day{1}", days, days == 1 ? null : "s"));
            if (hours > 0)
                parts.Add(string.Format("{0} hour{1}", hours, hours == 1 ? null : "s"));
            if (minutes > 0)
                parts.Add(string.Format("{0} minute{1}", minutes, minutes == 1 ? null : "s"));
            if (fractionalSeconds.Equals(0D))
            {
                switch (seconds)
                {
                    case 0:
                        // Only write "0 seconds" if we haven't written anything at all.
                        if (parts.Count == 0)
                            parts.Add("0 seconds");
                        break;
    
                    case 1:
                        parts.Add("1 second");
                        break;
    
                    default:
                        parts.Add(seconds + " seconds");
                        break;
                }
            }
            else
            {
                parts.Add(string.Format("{0}{1:.###} seconds", seconds, fractionalSeconds));
            }
    
            string resultString = string.Join(", ", parts);
            return isNegative ? "(negative) " + resultString : resultString;
        }
    }
    
        18
  •  0
  •   Rob    7 年前

    如果希望持续时间格式类似于youtube,请给定秒数

    int[] duration = { 0, 4, 40, 59, 60, 61, 400, 4000, 40000, 400000 };
    foreach (int d in duration)
    {
        Console.WriteLine("{0, 6} -> {1, 10}", d, d > 59 ? TimeSpan.FromSeconds(d).ToString().TrimStart("00:".ToCharArray()) : string.Format("0:{0:00}", d));
    }
    

    输出:

         0 ->       0:00
         4 ->       0:04
        40 ->       0:40
        59 ->       0:59
        60 ->       1:00
        61 ->       1:01
       400 ->       6:40
      4000 ->    1:06:40
     40000 ->   11:06:40
    400000 -> 4.15:06:40
    
        19
  •  0
  •   Piees    7 年前

    我想返回一个字符串,如“1天2小时3分钟”,并考虑例如天或分钟数是否为0,然后不显示它们。幸亏 John Rasch

    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 ");
    
        20
  •  0
  •   tometchy    3 年前

    没有人展示过使用十进制格式说明符的方法,这是我最喜欢的一种,尤其是当与字符串插值一起使用时- https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings?redirectedfrom=MSDN#decimal-format-specifier-d

    $"{time.Hours:D2}:{time.Minutes:D2}:{time.Seconds:D2}.{time.Milliseconds:D3}"
    // Sample output: 00:00:09.200
    

    当然,您可以用一些助手方法来包装它。