当前位置: 动力学知识库 > 问答 > 编程问答 >

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;

sec = 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);
分享给朋友:
您可能感兴趣的文章:
随机阅读: