c# - 格式异常 - 日期时间和小时

标签 c# formatting

我想从日期时间获取小时数。因此,如果是下午 1 点,则只有 1,如果是晚上 10 点,则为 10。因此,在 1-9 小时内没有前导零

所以我尝试这样做

DateTime test= DateTime.Now;
Console.WriteLine(test.ToString("h"));

我明白了

System.FormatException was unhandled
Message=Input string was not in a correct format. Source=mscorlib
StackTrace: at System.DateTimeFormat.GetRealFormat(String format, DateTimeFormatInfo dtfi) at System.DateTimeFormat.ExpandPredefinedFormat(String format, DateTime& dateTime, DateTimeFormatInfo& dtfi, TimeSpan& offset) at System.DateTimeFormat.Format(DateTime dateTime, String format, DateTimeFormatInfo dtfi, TimeSpan offset) at System.DateTimeFormat.Format(DateTime dateTime, String format, DateTimeFormatInfo dtfi) at System.DateTime.ToString(String format) at ConsoleApplication1.Program.Main(String[] args) in C:\Users\chobo2\Documents\Visual Studio 2010\Projects\ConsoleApplication1\ConsoleApplication1\Program.cs:line 21 at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() InnerException:

最佳答案

来自 MSDN (“h”自定义格式说明符):

If the "h" format specifier is used without other custom format specifiers, it is interpreted as a standard date and time format specifier and throws a FormatException. For more information about using a single format specifier, see Using Single Custom Format Specifiers later in this topic.

您可以使用以下内容(as described 在“使用单个自定义格式说明符)”中:

To use any of the custom date and time format specifiers as the only specifier in a format string (that is, to use the "d", "f", "F", "g", "h", "H", "K", "m", "M", "s", "t", "y", "z", ":", or "/" custom format specifier by itself), include a space before or after the specifier, or include a percent ("%") format specifier before the single custom date and time specifier.

因此,您可以执行以下操作:

DateTime test= DateTime.Now;
Console.WriteLine(test.ToString("{0:%h}")); // From the document, adds precision
Console.WriteLine(test.ToString("%h")); // Will also work

关于c# - 格式异常 - 日期时间和小时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3080854/

相关文章:

Excel:如果在另一列中发现重复的单元格值,则突出显示绿色

java - 当文本是字段时,如何为文本 "text"添加下划线?

c# - .net core 3.0 的 MVVM 框架

c# - Xamarin : Get MvxRecyclerView working

python - 在 Python 中重写 logging.Formatter

php - MySQL/PHP - 在数字周围加上引号会破坏任何查询吗?

c# - Linq 2 Sql DateTime 格式为字符串 yyyy-MM-dd

c# - 在 DDD 中打包存储库及其接口(interface)

c# - async/await - 这种理解是否正确?

c# - 主菜单中缺少 Visual Studio TEST