如何将秒转换为(小时:分钟:秒:毫秒)时间?
假设我有80秒;. net中有没有专门的类/技术可以让我把这80秒转换成(00h:00m:00s:00ms)格式,比如convert。ToDateTime之类的?
如何将秒转换为(小时:分钟:秒:毫秒)时间?
假设我有80秒;. net中有没有专门的类/技术可以让我把这80秒转换成(00h:00m:00s:00ms)格式,比如convert。ToDateTime之类的?
当前回答
如果我们有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)
其他回答
对于。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以避免异常。
这将以hh:mm:ss格式返回
public static string ConvertTime(long secs)
{
TimeSpan ts = TimeSpan.FromSeconds(secs);
string displayTime = $"{ts.Hours}:{ts.Minutes}:{ts.Seconds}";
return displayTime;
}
在VB。NET,但是在c#中也是一样的:
Dim x As New TimeSpan(0, 0, 80)
debug.print(x.ToString())
' Will print 00:01:20
得到总秒数
var i = TimeSpan.FromTicks(startDate.Ticks).TotalSeconds;
并从秒获取datetime
var thatDateTime = new DateTime().AddSeconds(i)
如果您知道您有一个秒数,您可以通过调用TimeSpan来创建一个TimeSpan值。FromSeconds:
TimeSpan ts = TimeSpan.FromSeconds(80);
您可以获取天、小时、分钟或秒的数量。或者使用一个ToString重载以任何您喜欢的方式输出它。