DateTime的小时?24小时格式

eut*_*her 143 c# datetime

所以我有这个DateTime?而我想要做的是获得小时,但以24小时格式显示.
例如:
如果小时是下午2:20:23,我想将其转换为14:20就是这样.

我正在使用Visual C#.请任何想法,谢谢.

我有类似的东西

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

        string retornar = "";
          //here goes what i need
    }
Run Code Online (Sandbox Code Playgroud)

vto*_*ola 242

您可以使用下面的代码获得所需的结果.Two'H'in HH是24小时格式.

return fechaHora.Value.ToString("HH:mm");
Run Code Online (Sandbox Code Playgroud)

  • 描述为什么这个工作将是有用的.如HH为24小时格式为hh为12小时. (4认同)

Man*_*ani 127

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

请参阅链接以了解DateTime中的其他格式化程序.


Dan*_*Tao 17

使用ToString("HH:mm")肯定会为你提供你想要的字符串.

如果您希望当前小时/分钟为数字,则不需要字符串操作; 你可以使用该TimeOfDay属性:

TimeSpan timeOfDay = fechaHora.TimeOfDay;
int hour = timeOfDay.Hours;
int minute = timeOfDay.Minutes;
Run Code Online (Sandbox Code Playgroud)

  • 您不需要 TimeOfDay。您可以使用 fechaHora.Hour 并获取 0 到 23 之间的数字。 (2认同)

Mik*_*scu 5

尝试这个:

//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);
}
Run Code Online (Sandbox Code Playgroud)