Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 464
wmazizi Avatar asked May 22 '16 05:05

wmazizi


People also ask

How do you write 12 am in 24-hour format?

Converting from 12 hour to 24 hour clock 12:00 AM = 0:00. 12:15 AM = 0:15.

How do I convert 12-hour format to 24-hour format in SQL?

In SQL Server 2012, we can use Format function to have suitable date time format. Use capital letter 'HH:mm:ss' for 24 hour date time format.

What is 12.30 am in 24-hour format?

Add 12 to the first hour of the day and include "AM." In 24-hour time, midnight is signified as 00:00. So, for midnight hour, add 12 and the signifier "AM" to convert to 12-hour time. This means that, for example, 00:13 in 24-hour time would be 12:13 AM in 12-hour time.


1 Answers

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"
like image 111
Siyavash Hamdi Avatar answered Sep 28 '22 22:09

Siyavash Hamdi