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

cho*_*bo2 6 c# formatting

我想从日期时间开始.因此,如果是下午1点,如果是晚上10点那么它将是10,因此在1-9小时内没有前导零.

所以我试着这样做

DateTime test= DateTime.Now;
Console.WriteLine(test.ToString("h"));
Run Code Online (Sandbox Code Playgroud)

我明白了

System.FormatException未处理
Message =输入字符串格式不正确.来源= mscorlib程序
StackTrace:System.DateTimeFormat.GetRealFormat(String格式,DateTimeFormatInfo dtfi),System.DateTimeFormat.ExpandPredefinedFormat(String格式,DateTime&dateTime,DateTimeFormatInfo&dtfi,TimeSpan&offset),System.DateTimeFormat.Format(DateTime dateTime,String format,DateTimeFormatInfo dtfi, System.DateTimeFormat.Format(DateTime dateTime,String format,DateTimeFormatInfo dtfi)中的System.DateTime.ToString(String格式)处于System:Application.Program.Main(String [] args)中的C:\ Users\chobo2\Documents中的TimeSpan偏移量\ Visual Studio 2010\Projects\ConsoleApplication1\ConsoleApplication1\Program.cs:System.AppDomain的System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly,String [] args)第21行.System.Threading.ExecutionContext.Run上的System.Threading.ThreadHelper.ThreadStart_Context(Object state)中的Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()中的ExecuteAssembly(String assemblyFile,Evidence assemblySecurity,String [] args)(ExecutionContext executionContext,ContextCallback) System.Threading.ThreadHelper.ThreadStart()中的System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback回调,对象状态)的回调,对象状态,布尔值ignoreSyncCtx):InnerException:System.Threading.ThreadHelper.ThreadStart()中的System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback回调,对象状态)的ExecutionContext.Run(ExecutionContext executionContext,ContextCallback回调,Object状态,Boolean ignoreSyncCtx):InnerException:System.Threading.ThreadHelper.ThreadStart()中的System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback回调,对象状态)的ExecutionContext.Run(ExecutionContext executionContext,ContextCallback回调,Object状态,Boolean ignoreSyncCtx):InnerException:

Ode*_*ded 14

MSDN("h"自定义格式说明符):

如果使用"h"格式说明符而没有其他自定义格式说明符,则将其解释为标准日期和时间格式说明符并抛出FormatException.有关使用单个格式说明符的详细信息,请参阅本主题后面的使用单个自定义格式说明符.

您可以使用以下内容( "使用单个自定义格式说明符"中所述):

使用任何自定义日期和时间格式说明符作为格式字符串中的唯一说明符(即使用"d","f","F","g","h","H", "K","m","M","s","t","y","z",":"或"/"自定义格式说明符)包括在之前或之后的空格说明符,或在单个自定义日期和时间说明符之前包含百分比("%")格式说明符.

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

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