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
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"));
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.
Try this:
Console.WriteLine("{0:D2}:{1:D2}", duration.Minutes, duration.Seconds);
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.
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.
TimeSpan t = TimeSpan.Parse("13:45:43");
Console.WriteLine(@"Timespan is {0}", String.Format(@"{0:yy\:MM\:dd\:hh\:mm\:ss}", t));