开发者

create a time based on seconds in c#

If i have a seconds as a int like 70 80 or 2500 how do i show it as a time of format hh:mm:ss using the most easiest way. I know i can make a separate method for it and i did but i wanna check if there is any lib func already available for it. THis is the method i created and it works.

private void MakeTime(int seconds)
    {
        int min = 0;
        int sec = seconds;
        int hrs = 0;
        if (seconds > 59)
        {
            min = seconds / 60;
            se开发者_JS百科c = seconds % 60;
        }
        if (min > 59)
        {
            hrs = min / 60;
            min = min % 60;
        }
        string a = string.Format("{0:00}:{1:00}:{2:00}", hrs, min, sec);
    }

This is the function i am using now. it works but still i have a feeling that a single line call will do this. Any one know of any?


You can use TimeSpan

TimeSpan t = TimeSpan.FromSeconds(seconds);

and

use t.Hours, t.Minutes and t.Seconds to format the string how ever you want.


TimeSpan.FromSeconds(seconds).ToString("hh:mm:ss")


Try this:

        TimeSpan t = TimeSpan.FromSeconds(seconds);
        string a = string.Format("{0:00}:{1:00}:{2:00}", t.Hours, t.Minutes, t.Seconds);


    TimeSpan ts = TimeSpan.FromSeconds(666);
    string time = ts.ToString();


Use a TimeSpan:

TimeSpan ts = TimeSpan.FromSeconds(70);


Any reason why you can't just use DateTime instead, like this?

        DateTime t = new DateTime(0);
        Console.WriteLine("Enter # of seconds");
        string userSeconds = Console.ReadLine();
        t = t.AddSeconds(Int32.Parse(userSeconds));
        Console.WriteLine("As HH:MM:SS = {0}:{1}:{2}", t.Hour, t.Minute, t.Second);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜