Dùng DateTime.Parse + ToString("HH:mm") hoặc DateTime.TryParseExact để chuyển format 12h → 24h.
Ví dụ minh họa
using System;
using System.Globalization;
class Program
{
static void Main()
{
string[] times12h = { "05:00 PM", "12:30 AM", "12:30 PM", "09:15 AM", "11:59 PM" };
foreach (string timeStr in times12h)
{
// Parse với format 12h
if (DateTime.TryParseExact(timeStr, "hh:mm tt",
CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime dt))
{
// Format 24h
string time24h = dt.ToString("HH:mm", CultureInfo.InvariantCulture);
Console.WriteLine($"{timeStr,-10} → {time24h}");
}
else
{
Console.WriteLine($"{timeStr,-10} → INVALID FORMAT");
}
}
// Chuyển ngược 24h → 12h
Console.WriteLine("\n--- 24h → 12h ---");
string[] times24h = { "17:00", "00:30", "12:30", "09:15", "23:59" };
foreach (string timeStr in times24h)
{
if (DateTime.TryParseExact(timeStr, "HH:mm",
CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime dt))
{
string time12h = dt.ToString("hh:mm tt", CultureInfo.InvariantCulture);
Console.WriteLine($"{timeStr,-5} → {time12h}");
}
}
}
}
Kết quả đầu ra
05:00 PM → 17:00 12:30 AM → 00:30 12:30 PM → 12:30 09:15 AM → 09:15 11:59 PM → 23:59 --- 24h → 12h --- 17:00 → 05:00 PM 00:30 → 12:30 AM 12:30 → 12:30 PM 09:15 → 09:15 AM 23:59 → 11:59 PM
Format specifiers: hh (12h), HH (24h), mm (phút), tt (AM/PM). Luôn dùng CultureInfo.InvariantCulture để tránh locale issues.