将秒转换为(小时:分钟:秒:毫秒)时间的最佳方法是什么?
假设我有80秒,.NET中有没有什么专门的类/技术可以让我把这80秒转换成像DateTime之类的(00h:00m:00s:00ms)格式?
发布于 2009-01-21 00:19:40
对于.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");
(来自Nick Molyneux)确保秒数小于TimeSpan.MaxValue.TotalSeconds
以避免异常。
发布于 2013-07-23 13:53:03
对于.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");
有关更多信息,请查看Custom TimeSpan Format Strings
发布于 2009-01-21 00:20:07
如果您知道您的秒数,您可以通过调用TimeSpan.FromSeconds来创建TimeSpan值:
TimeSpan ts = TimeSpan.FromSeconds(80);
然后您可以获得天数、小时数、分钟数或秒数。或者使用ToString重载之一以任何您喜欢的方式输出它。
https://stackoverflow.com/questions/463642
复制相似问题