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

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

    If you want the duration format similar to youtube, given the number of seconds

    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));
    }
    

    Output:

         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
    

提交回复
热议问题