开发者

Hour from DateTime? in 24 hours format

So i have this DateTime? and what i want to do is to obtain the hour but开发者_JAVA百科 show it in 24 hours format.

For example:

If the hour is 2:20:23 p.m. i want to convert it to 14:20 and that's it.

I'm working with Visual C#. Any ideas please, thank you.

I have something like this

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

    string retornar = "";
    //here goes what i need
}


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);
}


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜