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.
Converting from 12 hour to 24 hour clock 12:00 AM = 0:00. 12:15 AM = 0:15.
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.
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With