how to convert seconds in min:sec format

0 votes
asked Sep 8, 2010 by ramesh

how to convert seconds in Minute:Second format

9 Answers

0 votes
answered Sep 8, 2010 by michel-triana
var seconds = 60;
//10,000 ticks in a millisecond
var ticks = seconds*10000*1000;
DateTime dt = new DateTime(ticks);
dt.ToString("mm:ss");
0 votes
answered Sep 8, 2010 by x2
int totalSeconds = 222;
int seconds = totalSeconds % 60;
int minutes = totalSeconds / 60;
string time = minutes + ":" + seconds;
0 votes
answered Sep 8, 2010 by chrisbd

Simple maths. 60 seconds to a minute.

int mins = totalseconds/60;
int secs = totalseconds % 60;

Console.Writeline(string.Format("{0}:{1}", mins, secs));
0 votes
answered Sep 8, 2010 by jon-skeet

Something like this:

string minSec = string.Format("{0}:{1:00}", seconds / 60, seconds % 60);

Note that that will ensure the seconds are always displayed as two digits, e.g. "2:05" for 125 seconds. The minutes aren't currently treated the same way, but of course they could be.

This doesn't deal well with negative numbers. If your seconds may be negative, you may want something like this:

string minSec = string.Format("{0}:{1:00}", seconds / 60, 
                              (Math.Abs(seconds)) % 60);

Finally, will you always have less than an hour of seconds? It might look odd to see "80:00" when you really mean "1:20:00" for example.

0 votes
answered Sep 8, 2010 by lasse-espeholt

A versatile version is to use TimeSpan like this:

var span = new TimeSpan(0, 0, seconds); //Or TimeSpan.FromSeconds(seconds); (see Jakob C´s answer)
var yourStr = string.Format("{0}:{1:00}", 
                            (int)span.TotalMinutes, 
                            span.Seconds);
0 votes
answered Sep 8, 2010 by jakob-christensen

Just for completeness I will add an answer using TimeSpan (works as of .NET 4.0):

int seconds = 1045;
var timespan = TimeSpan.FromSeconds(seconds);            
Console.WriteLine(timespan.ToString(@"mm\:ss"));
0 votes
answered Sep 8, 2010 by grif

An alternative way to display the seconds as e.g. "2:05" could be to use PadLeft.

string time = minutes.ToString() + ":" + seconds.ToString().PadLeft(2,'0');
0 votes
answered Sep 8, 2010 by siva-gopal
double seconds=125;    
TimeSpan.FromSeconds(seconds).ToString() 

will give you : 00:02:05. As per my understanding this built-in solution is more extensible, since it can give you hours too, without any plumbing of the logic.

0 votes
answered Sep 15, 2017 by haohmaru

What works for me...

public static string SecondsToMinutes(int seconds)
{
   var ts = new TimeSpan(0, 0, seconds);                
   return new DateTime(ts.Ticks).ToString(seconds >= 3600 ? "hh:mm:ss" : "mm:ss");
}
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...