如何将秒转换为(小时:分钟:秒:毫秒)时间?

假设我有80秒;. net中有没有专门的类/技术可以让我把这80秒转换成(00h:00m:00s:00ms)格式,比如convert。ToDateTime之类的?


当前回答

对于。net > 4.0你可以使用

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

如果你想要日期时间格式,你也可以这样做

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

有关更多信息,您可以检查自定义TimeSpan格式字符串

其他回答

对于。net > 4.0你可以使用

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

如果你想要日期时间格式,你也可以这样做

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

有关更多信息,您可以检查自定义TimeSpan格式字符串

得到总秒数

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

并从秒获取datetime

var thatDateTime = new DateTime().AddSeconds(i)

我建议您为此使用TimeSpan类。

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

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

输出:

00:01:20
10054.07:43:32

如果我们有DateTime. addseconds(),为什么人们需要TimeSpan和DateTime ?

var dt = new DateTime(2015, 1, 1).AddSeconds(totalSeconds);

日期是任意的。 totalSeconds可以大于59,它是一个double。 然后你可以使用DateTime.ToString()格式化你的时间:

dt.ToString("H:mm:ss");

如果totalSeconds < 0或> 59:

new DateTime(2015, 1, 1, 0, 0, totalSeconds)

TimeSpan构造函数允许以秒为单位传递。只需声明一个TimeSpan类型的变量(秒数)。例:

TimeSpan span = new TimeSpan(0, 0, 500);
span.ToString();