Format Exception-DateTime and Clock

I want to get the clock from datetime. So if it is 1pm, it will be only 1, if it is 10pm, it will be 10. Thus, no leading zero will be placed in hours 1-9

So I tried to do it

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

I get it

System.FormatException was not handled
Message = The input string was not in the correct format. Source = mscorlib
Stack trace: a System.DateTimeFormat.GetRealFormat (String format, DateTimeFormatInfo dtfi) in System.DateTimeFormat.ExpandPredefinedFormat (String format, DateTime & DATETIME, DateTimeFormatInfo & dtfi, TimeSpan & displacement) in System.DateTimeFormat.Format (DateTime dateTime, String format , DateTimeFormatInfo dtfi, TimeSpan offset) in System.DateTimeFormat.Format (DateTime dateTime, String format, DateTimeFormatInfo dtfi) in System.DateTime.ToString (String format) in ConsoleApplication1.Program.Main (String [] args) in C: \ Users \ chobo2 \ Documents \ Visual Studio 2010 \ Projects \ ConsoleApplication1 \ ConsoleApplication1 \ Program.cs: lines 21 in System.AppDomain._nExecuteAssembly (RuntimeAssembly assembly, String [] args) in System.AppDomain.ExecuteAssembly (String assembly, proof StringSecurity [] args) at Microsoft. VisualStudio.HostingProcess.HostProc.RunUsersAssembly () in System.Threading.ThreadHelper.ThreadStart_Context (Object state) in System.Threading.ExecutionContext.Run (ExecutionContext executeContext, ContextCallback callback, object state, boolean value ignoreSyncThreadtext .Run (ExecutionContext executeContext, ContextCallback callback, object state) in System.Threading.ThreadHelper.ThreadStart () InnerException:

+6
c # formatting
source share
1 answer

From MSDN (custom format specifier h):

If the format specifier "h" is used without other specifiers of a special format, it is interpreted as a standard specifier of the date and time format and throws a FormatException. For more information about using the single format specifier, see the "Using Specification of Individual Custom Formats" section later in this section.

You can use the following ( as described in the “Using Individual Custom Format Specifiers” section):

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

So you can do the following:

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

All Articles