Convert 12-hour format to 24-hour format in C#

wmazizi picture wmazizi · May 22, 2016 · Viewed 20.3k times · Source

How to convert 12-hour format to 24-hour format in DateTime format.

I already tried to convert the DateTime to string (24-hour format) and convert it back to Datetime format but it is not working.

Answer

Siyavash Hamdi picture Siyavash Hamdi · May 22, 2016

Using extension methods are also good idea.

public static class MyExtensionClass
{
    public static string ToFormat12h(this DateTime dt)
    {
        return dt.ToString("yyyy/MM/dd, hh:mm:ss tt");
    }

    public static string ToFormat24h(this DateTime dt)
    {
        return dt.ToString("yyyy/MM/dd, HH:mm:ss");
    }
}

Then you can use these 2 methods as following:

var dtNow = DateTime.Now;

var h12Format = dtNow.ToFormat12h();    // "2016/05/22, 10:28:00 PM"
var h24Format = dtNow.ToFormat24h();    // "2016/05/22, 22:28:00"