Hour from DateTime? in 24 hours format

前端 未结 5 730
迷失自我
迷失自我 2020-12-01 03:57

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

相关标签:
5条回答
  • 2020-12-01 04:28
    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.

    0 讨论(0)
  • 2020-12-01 04:36

    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");
    
    0 讨论(0)
  • 2020-12-01 04:42

    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;
    
    0 讨论(0)
  • 2020-12-01 04:45
    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 讨论(0)
  • 2020-12-01 04:48

    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);
    }
    
    0 讨论(0)
提交回复
热议问题