Sử dụng struct TimeSpan để biểu diễn khoảng thời gian, kết hợp TimeSpan.FromSeconds và format string.
Cách đơn giản nhất
double totalSeconds = 3752; // 1h 2m 32s
TimeSpan ts = TimeSpan.FromSeconds(totalSeconds);
string formatted = $"{ts.Hours:D2}h:{ts.Minutes:D2}m:{ts.Seconds:D2}s:{ts.Milliseconds:D3}ms";
Console.WriteLine(formatted); // 01h:02m:32s:000ms
Format chuẩn (TimeSpan.ToString)
// Format chuẩn: hh\:mm\:ss\.fff
Console.WriteLine(ts.ToString(@"hh\:mm\:ss\.fff")); // 01:02:32.000
// Tuỳ chỉnh
Console.WriteLine(ts.ToString("h'h 'm'm 's's 'fff'ms'")); // 1h 2m 32s 000ms
Ví dụ hoàn chỉnh
static string FormatSeconds(double seconds)
{
TimeSpan ts = TimeSpan.FromSeconds(seconds);
return $"{ts.Hours:D2}:{ts.Minutes:D2}:{ts.Seconds:D2}.{ts.Milliseconds:D3}";
}
static void Main()
{
Console.WriteLine(FormatSeconds(6)); // 00:00:06.000
Console.WriteLine(FormatSeconds(65)); // 00:01:05.000
Console.WriteLine(FormatSeconds(3600)); // 01:00:00.000
Console.WriteLine(FormatSeconds(3752.123)); // 01:02:32.123
Console.WriteLine(FormatSeconds(90061)); // 25:01:01.000 (Hours > 24)
Console.ReadLine();
}
Lưu ý về TimeSpan
Hours,Minutes,Seconds: Chỉ thành phần đó (Hours có thể > 23).TotalHours,TotalMinutes,TotalSeconds: Tổng cộng (double).Milliseconds: Chỉ phần mili-giây (0-999). DùngTotalMillisecondscho tổng mili-giây.- Độ chính xác:
TimeSpandùng ticks (100ns), đủ chính xác cho hầu hết ứng dụng.
Parse ngược lại
string input = "01:02:32.123";
if (TimeSpan.TryParseExact(input, @"hh\:mm\:ss\.fff", null, out TimeSpan ts))
{
double seconds = ts.TotalSeconds; // 3752.123
}
Extension Method tiện lợi
public static class TimeSpanExtensions
{
public static string ToReadableString(this TimeSpan ts)
{
if (ts.TotalHours >= 1)
return $"{ts.Hours}h {ts.Minutes}m {ts.Seconds}s";
if (ts.TotalMinutes >= 1)
return $"{ts.Minutes}m {ts.Seconds}s";
return $"{ts.Seconds}.{ts.Milliseconds:D3}s";
}
}
// Usage
var ts = TimeSpan.FromSeconds(3752);
Console.WriteLine(ts.ToReadableString()); // 1h 2m 32s