Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hour from DateTime? in 24 hours format

Tags:

c#

datetime

People also ask

How do I use 24 hour format in datetime?

Two 'H' in HH is for 24-hour format. Description as to why this works would be useful. Such as HH for 24 hour format as hh for 12 hour.


You can get the desired result with the code below. Two 'H' in HH is for 24-hour format.

return fechaHora.Value.ToString("HH:mm");

date.ToString("HH:mm:ss"); // for 24hr format
date.ToString("hh:mm:ss"); // for 12hr format, it shows AM/PM

Refer this link for other Formatters in DateTime.


Using ToString("HH:mm") certainly gives you what you want as a string.

If you want the current hour/minute as numbers, string manipulation isn't necessary; you can use the TimeOfDay property:

TimeSpan timeOfDay = fechaHora.TimeOfDay;
int hour = timeOfDay.Hours;
int minute = timeOfDay.Minutes;

Try this:

//String.Format("{0:HH:mm}", dt);  // where dt is a DateTime variable

public static string FormatearHoraA24(DateTime? fechaHora)
{
    if (!fechaHora.HasValue)
        return "";

    return retornar = String.Format("{0:HH:mm}", (DateTime)fechaHora);
}