Search code examples
c#.netdatetimehour

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


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.


Solution

  • 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"