7

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.

bashrc
  • 4,725
  • 1
  • 22
  • 49
wmazizi
  • 99
  • 1
  • 1
  • 6

3 Answers3

10

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"
Siyavash Hamdi
  • 2,764
  • 2
  • 21
  • 32
9
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123); 

dt.ToString("dd/MM/yyyy hh:mm:ss tt"); //12 HOUR FORMAT
dt.ToString("dd/MM/yyyy HH:mm:ss");    //24 HOUR FORMAT 
Rahul Jha
  • 1,131
  • 1
  • 10
  • 25
1

Check the following code.

string time = Console.ReadLine();
DateTime dt = Convert.ToDateTime(time);
String militaryDate = dt.ToString("HH:mm:sstt");
Console.Write(militaryDate);
Ataur Rahman Munna
  • 3,887
  • 1
  • 23
  • 34