开发者

how to convert seconds in min:sec format

how to con开发者_StackOverflow中文版vert seconds in Minute:Second format


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


int totalSeconds = 222;
int seconds = totalSeconds % 60;
int minutes = totalSeconds / 60;
string time = minutes + ":" + seconds;


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


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.


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.


var seconds = 60;
//10,000 ticks in a millisecond
var ticks = seconds*10000*1000;
DateTime dt = new DateTime(ticks);
dt.ToString("mm:ss");


Simple maths. 60 seconds to a minute.

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

Console.Writeline(string.Format("{0}:{1}", mins, secs));


Not strictly answering the original question, but in case anyone (or myself) in the future comes here from google wanting to format a float with milliseconds as well:

float secs = 23.69;
string m_ss_mmm = string.Format("{0}:{1:00}.{2:000}", (int)secs / 60, (int)(secs % 60), (secs - ((int)secs)) * 1000);

Result:

0:23.690


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


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


If you need it as float or double:

float seconds = 339;
float totalTimeInMins = (float) (Math.Floor(seconds / 60) + (seconds % 60) / 100);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜