C# 如何从 System.DateTime.Now.Hour 获取 24 小时数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13847367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:58:31  来源:igfitidea点击:

How to get 24 hours number from System.DateTime.Now.Hour?

c#datetime

提问by KentZhou

I want to get the current hour number with 0-24from System.DateTime.Now.Hour. I am not sure if it will return an integer between 0-12or 0-24. How do I make sure I will get an integer between 0-24?

我想用0-24from 获取当前小时数System.DateTime.Now.Hour。我不确定它是否会返回0-12或之间的整数0-24。我如何确保我会得到一个整数0-24

回答by Tim Schmelter

DateTime.Hour Property

DateTime.Hour 属性

The value of the Hour property is always expressed using a 24-hour clock. To retrieve a string that represents the hour of a date and time using a 12-hour clock, call the DateTime.ToString(String) or DateTime.ToString(String, IFormatProvider) method with the "h" custom format specifier. For example:

Hour 属性的值始终使用 24 小时制表示。要使用 12 小时制检索表示日期和时间的小时的字符串,请使用“h”自定义格式说明符调用 DateTime.ToString(String) 或 DateTime.ToString(String, IFormatProvider) 方法。例如:

and

The hour component, expressed as a value between 0 and 23.

小时部分,表示为0 到 23之间的值。

回答by Soner G?nül

From MSDN;

来自 MSDN;

   DateTime date1 = new DateTime(2008, 4, 1, 18, 53, 0);
   Console.WriteLine(date1.ToString("%h"));              // Displays 6 
   Console.WriteLine(date1.ToString("h tt"));            // Displays 6 PM

回答by Trisped

If you are trying to get a specific string version of a DateTime object I suggest using either a custom date and time format stringor a standard date and time format string.

如果您尝试获取 DateTime 对象的特定字符串版本,我建议使用自定义日期和时间格式字符串标准日期和时间格式字符串

I usually use dateTimeVar.ToString("yyyy/MM/dd HH:mm:ss.ffff zzz");though you may want Kinstead of zzz

我通常使用dateTimeVar.ToString("yyyy/MM/dd HH:mm:ss.ffff zzz");虽然你可能想要K而不是zzz