2010-06-20 15 views
6

我想從日期時間獲得小時。所以,如果是下午1時它將是1,如果是晚上10點這將是10所以上1-9小時格式異常 - 日期時間和小時

沒有前導零是地方於是,我就這樣做

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

我得到此

System.FormatException了未處理
消息=輸入字符串的不以 正確的格式。源= mscorlib程序
堆棧跟蹤: 在System.DateTimeFormat.GetRealFormat(字符串 格式,的DateTimeFormatInfo dtfi) 在System.DateTimeFormat.ExpandPredefinedFormat(字符串 格式,日期時間& DATETIME, 的DateTimeFormatInfo & dtfi,時間跨度& 偏移) 在System.DateTimeFormat.Format(DateTime的 日期時間,字符串格式, 的DateTimeFormatInfo dtfi,時間跨度 偏移) 在System.DateTimeFormat.Format(DateTime的 日期時間,字符串格式, DateTimeFor matInfo dtfi) 在System.DateTime.ToString(字符串 格式) 在ConsoleApplication1.Program.Main(字符串[] 參數)在 C:\用戶\ chobo2 \文件\視覺 工作室 2010 \項目\ ConsoleApplication1 \ ConsoleApplication1 \的Program.cs:線在System.AppDomain._nExecuteAssembly(RuntimeAssembly 組件,字串[] args) 在System.AppDomain.ExecuteAssembly(字符串 assemblyFile,證據 assemblySecurity,字串[] args) 在微軟.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.Thre adStart_Context(對象 狀態) 在System.Threading.ExecutionContext.Run(的ExecutionContext 的ExecutionContext,ContextCallback 回調,對象的狀態,布爾 ignoreSyncCtx) 在System.Threading.ExecutionContext.Run(的ExecutionContext 的ExecutionContext,ContextCallback 回調,對象狀態) 在System.Threading.ThreadHelper.ThreadStart() 的InnerException:

回答

13

MSDN(下稱 「H」 自定義格式說明):

如果使用「h」格式說明符而沒有其他自定義格式說明符,則它將被解釋爲標準日期和時間格式說明符並引發FormatException。有關使用單個格式說明符的更多信息,請參閱本主題後面的使用單個自定義格式說明符。

你可以(在「使用單個自定義格式說明as described)」使用以下內容:

使用任何自定義日期和時間格式說明符作爲格式字符串的唯一符(即是使用「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 
+0

雅,我發現一些關於%H,但不明白爲什麼你需要它。 http://msdn.microsoft.com/en-us/library/system.datetime.hour.aspx – chobo2 2010-06-20 20:43:05

+0

+1。雖然不應該是'Console.WriteLine(test.ToString(「%h」));'? – 2010-06-20 20:43:20

+0

@David Neale - 都會工作。 「0:」是一個精度說明符,以防萬一。 – Oded 2010-06-20 20:45:11