C# + Format TimeSpan

后端 未结 10 669
忘掉有多难
忘掉有多难 2020-12-09 01:44

I am trying to format a TimeSpan element in the format of \"[minutes]:[seconds]\". In this format, 2 minutes and 8 seconds would look like \"02:08\". I have tried a variety

相关标签:
10条回答
  • 2020-12-09 01:48

    Try this:

    DateTime startTime = DateTime.Now;
    // Do Stuff
    TimeSpan duration = DateTime.Now.Subtract(startTime);
    
    Console.WriteLine("[paragraph of information] Total Duration: " + duration.Minutes.ToString("00") + ":" + duration.Seconds.ToString("00"));
    
    0 讨论(0)
  • 2020-12-09 01:51

    You can use the below code.

    TimeSpan tSpan = TimeSpan.FromSeconds(allTotalInMinutes);
    string tTime = string.Format("{1:D2}:{2:D2}", tSpan.Minutes, tSpan.Seconds);
    

    It will show ie 34:45 format.

    Hope it will help you.

    0 讨论(0)
  • 2020-12-09 01:54

    Try this:

    Console.WriteLine("{0:D2}:{1:D2}", duration.Minutes, duration.Seconds);
    
    0 讨论(0)
  • 2020-12-09 01:58

    The date and time format strings only apply to DateTime and DateTimeOffset. Yo can use a normal format string, though:

    string.Format("{0}:{1:00}", Math.Truncate(duration.TotalMinutes), duration.Seconds)
    

    Note that using TotalMinutes here ensures that the result is still correct when it took longer than 60 minutes.

    0 讨论(0)
  • 2020-12-09 02:00

    Based on this MSDN page describing the ToString method of TimeSpan, I'm somewhat surprised that you can even compile the code above. TimeSpan doesn't have a ToString() overload that accepts only one string.

    The article also shows a function you can coyp and use for formatting a TimeSpan.

    0 讨论(0)
  • 2020-12-09 02:03
    TimeSpan t = TimeSpan.Parse("13:45:43");
    Console.WriteLine(@"Timespan is {0}", String.Format(@"{0:yy\:MM\:dd\:hh\:mm\:ss}", t));
    
    0 讨论(0)
提交回复
热议问题