So i have this DateTime? and what i want to do is to obtain the hour but show it in 24 hours format.
For example:
If the hour is 2:20:23 p.m. i want to convert it to
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.
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");
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, if your input is string
For example
string input= "13:01";
string[] arry = input.Split(':');
string timeinput = arry[0] + arry[1];
private string Convert24To12HourInEnglish(string timeinput)
{
DateTime startTime = new DateTime(2018, 1, 1, int.Parse(timeinput.Substring(0, 2)),
int.Parse(timeinput.Substring(2, 2)), 0);
return startTime.ToString("hh:mm tt");
}
out put: 01:01
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);
}