将秒转换为 (Hour:Minutes:Seconds:Milliseconds) 时间的最佳方法是什么? [英] What is the best way to convert seconds into (Hour:Minutes:Seconds:Milliseconds) time?

查看:30
本文介绍了将秒转换为 (Hour:Minutes:Seconds:Milliseconds) 时间的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将秒转换为 (Hour:Minutes:Seconds:Milliseconds) 时间的最佳方法是什么?

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

假设我有 80 秒,.NET 中是否有任何专门的类/技术可以让我将这 80 秒转换为 (00h:00m:00s:00ms) 格式,如 DateTime 或其他格式?

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?

推荐答案

对于 .Net <= 4.0 使用 TimeSpan 类.

For .Net <= 4.0 Use the TimeSpan class.

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,您可以使用

(As noted by Inder Kumar Rathore) 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");

(来自 Nick Molyneux)确保秒数小于 TimeSpan.MaxValue.TotalSeconds 以避免异常.

(From Nick Molyneux) Ensure that seconds is less than TimeSpan.MaxValue.TotalSeconds to avoid an exception.

这篇关于将秒转换为 (Hour:Minutes:Seconds:Milliseconds) 时间的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆