秒を(時間:分:秒:ミリ秒)の時間に変換するにはどうすればいいですか? 質問する

秒を(時間:分:秒:ミリ秒)の時間に変換するにはどうすればいいですか? 質問する

秒を(時間:分:秒:ミリ秒)の時間に変換するにはどうすればよいですか?

たとえば、80 秒あるとします。.NET には、その 80 秒を (00h:00m:00s:00ms) 形式などに変換できる特殊なクラスやテクニックはありますConvert.ToDateTimeか?

ベストアンサー1

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

TimeSpan.MaxValue.TotalSeconds(Nick Molyneux より)例外を回避するには、秒数がより小さいことを確認してください。

おすすめ記事