加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 17:36:26 所属栏目:百科 来源:网络整理
导读:我想从日期时间开始.因此,如果是下午1点,如果是晚上10点那么它将是10,因此在1-9小时内没有前导零. 所以我试着这样做 DateTime test= DateTime.Now;Console.WriteLine(test.ToString("h")); 我明白了 System.FormatException was unhandled Message=Input str
我想从日期时间开始.因此,如果是下午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,
DateTimeFormatInfo dtfi)
at System.DateTime.ToString(String
format)
at ConsoleApplication1.Program.Main(String[]
args) in
C:Userschobo2DocumentsVisual
Studio
2010ProjectsConsoleApplication1ConsoleApplication1Program.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,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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读