2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【C#.NET】TimeSpanを使って、秒から時間表示にする時の注意

Posted at

はじめに

725000秒を「 時間 : 分 : 秒 」に変換したい。

int timeSec = 725000;
Console.WriteLine(TimeSpan.FromSeconds(timeSec).ToString(@"hh\:mm\:ss")); // 09:23:20

よし!これでおっけ!

と思った方、ぜひこの記事を読んでください。

環境

  • Windows 11
  • Visual Studio 2022
  • C# ( .NET 6.0 )

本文

int timeSec = 725000;
Console.WriteLine(TimeSpan.FromSeconds(timeSec).ToString(@"hh\:mm\:ss")); // 09:23:20

実はこれ、の情報がカットされています!

int timeSec = 725000;
Console.WriteLine(TimeSpan.FromSeconds(timeSec).ToString(@"hh\:mm\:ss")); // 09:23:20
Console.WriteLine(TimeSpan.FromSeconds(timeSec).ToString(@"dd\:hh\:mm\:ss")); // 08:09:23:20

"dd"を追加することで、8日と9時間23分20秒であることが分かります。

日も時間として表示したい!!という場合は、時間を別途計算してあげることで、実現可能です。

int timeSec = 725000;

TimeSpan timeSpan = TimeSpan.FromSeconds(timeSec);
int hours = timeSpan.Days * 24 + timeSpan.Hours;

Console.WriteLine($"{hours}:{timeSpan.Minutes}:{timeSpan.Seconds}"); // 201:23:20

おわりに

少しでも、間違ってコードを書く人が減りますように!
読んでいただきありがとうございました。

参考

  • マイクロソフトドキュメント:カスタム TimeSpan 書式指定文字列

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?