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

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


当前回答

对于。net < 4.0 (e.x: Unity),你可以写一个扩展方法来拥有TimeSpan。ToString(字符串格式)行为,如。net > 4.0

public static class TimeSpanExtensions
{
    public static string ToString(this TimeSpan time, string format)
    {
        DateTime dateTime = DateTime.Today.Add(time);
        return dateTime.ToString(format);
    }
}

在你的代码中,你可以像这样使用它:

var time = TimeSpan.FromSeconds(timeElapsed);

string formattedDate = time.ToString("hh:mm:ss:fff");

通过这种方式,您可以简单地从代码的任何地方调用ToString来格式化任何TimeSpanobject。

其他回答

TimeSpan.FromSeconds(80);

http://msdn.microsoft.com/en-us/library/system.timespan.fromseconds.aspx

得到总秒数

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

并从秒获取datetime

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

对于。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格式字符串

这将以hh:mm:ss格式返回

 public static string ConvertTime(long secs)
    {
        TimeSpan ts = TimeSpan.FromSeconds(secs);
        string displayTime = $"{ts.Hours}:{ts.Minutes}:{ts.Seconds}";
        return displayTime;
    }

对于。net <= 4.0使用TimeSpan类。

TimeSpan t = TimeSpan.FromSeconds( secs );

string answer = string.Format("{0:D2}h:{1:D2}m:{2:D2}s:{3:D3}ms", 
                t.Hours, 
                t.Minutes, 
                t.Seconds, 
                t.Milliseconds);

(Inder Kumar Rathore)对于。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");

确保seconds小于TimeSpan.MaxValue.TotalSeconds以避免异常。