What is the best way to convert seconds into (Hour

2019-01-02 19:21发布

What is the best way to convert seconds into (Hour:Minutes:Seconds:Milliseconds) time?

Let's say I have 80 seconds, are there any specialized classes/techniques in .NET that would allow me to convert those 80 seconds into (00h:00m:00s:00ms) format like to DateTime or something?

标签: c# datetime
12条回答
初与友歌
2楼-- · 2019-01-02 20:02

For .NET > 4.0 you can use

TimeSpan time = TimeSpan.FromSeconds(seconds);

//here backslash is must to tell that colon is
//not the part of format, it just a character that we want in output
string str = time .ToString(@"hh\:mm\:ss\:fff");

or if you want date time format then you can also do this

TimeSpan time = TimeSpan.FromSeconds(seconds);
DateTime dateTime = DateTime.Today.Add(time);
string displayTime = date.ToString("hh:mm:tt");

For more you can check Custom TimeSpan Format Strings

查看更多
与君花间醉酒
3楼-- · 2019-01-02 20:05

The TimeSpan constructor allows you to pass in seconds. Simply declare a variable of type TimeSpan amount of seconds. Ex:

TimeSpan span = new TimeSpan(0, 0, 500);
span.ToString();
查看更多
长期被迫恋爱
5楼-- · 2019-01-02 20:11

I'd suggest you use the TimeSpan class for this.

public static void Main(string[] args)
{
    TimeSpan t = TimeSpan.FromSeconds(80);
    Console.WriteLine(t.ToString());

    t = TimeSpan.FromSeconds(868693412);
    Console.WriteLine(t.ToString());
}

Outputs:

00:01:20
10054.07:43:32
查看更多
冷夜・残月
6楼-- · 2019-01-02 20:11

In VB.NET, but it's the same in C#:

Dim x As New TimeSpan(0, 0, 80)
debug.print(x.ToString())
' Will print 00:01:20
查看更多
初与友歌
7楼-- · 2019-01-02 20:12

to get total seconds

var i = TimeSpan.FromTicks(startDate.Ticks).TotalSeconds;

and to get datetime from seconds

var thatDateTime = new DateTime().AddSeconds(i)
查看更多
登录 后发表回答