Quantcast
Channel: C#タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9517

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

$
0
0
はじめに 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 書式指定文字列

Viewing all articles
Browse latest Browse all 9517

Trending Articles