DateTime Formatting C# with Example
Standard DateTime Formatting DateTimeFormatInfo specifies a set of specifiers for simple date and time formatting. Every specifier correspond to a particular DateTimeFormatInfo format pattern. //Create datetime DateTime dt = new DateTime(2016,08,01,18,50,23,230); var t = String.Format("{0:t}", dt); // "6:50 PM" ShortTime // "8/1/2016" ShortDate var d = String.Format("{0:d}", dt); var T = String.Format("{0:T}", dt); // "6:50:23 PM" LongTime // "Monday, August 1, 2016" LongDate var D = String.Format("{0:D}", dt); // "Monday, August 1, 2016 6:50 PM" LongDate+ShortTime var f = String.Format("{0:f}", dt); var F = String.Format("{0:F}", dt); // "Monday, August 1, 2016 6:50:23 PM" FullDateTime // "8/1/2016 6:50 PM" ShortDate+ShortTime var g = String.Format("{0:g}", dt); // "8/1/2016 6:50:23 PM" ShortDate+LongTime var G = String.Format("{0:G}", dt); var m = String.Format("{0:m}", dt); // "August 1" MonthDay // "August 2016" YearMonth var y = String.Format("{0:y}", dt); // "SMon, 01 Aug 2016 18:50:23 GMT" RFC1123 var r = String.Format("{0:r}", dt); // "2016-08-01T18:50:23" SortableDateTime var s = String.Format("{0:s}", dt); var u = String.Format("{0:u}", dt); // "2016-08-01 18:50:23Z" UniversalSortableDateTime Custom DateTime Formatting There are following custom format specifiers: y (year) M (month) d (day) h (hour 12) H (hour 24) m (minute) s (second) f (second fraction) F (second fraction, trailing zeroes are trimmed) t (P.M or A.M) z (time zone). year var year = String.Format("{0:y yy yyy yyyy}", dt); // "16 16 2016 2016" month var month = String.Format("{0:M MM MMM MMMM}", dt); // "8 08 Aug August" var day = String.Format("{0:d dd ddd dddd}", dt); // "1 01 Mon Monday" day hour 12/24 var hour = String.Format("{0:h hh H HH}", dt); // "6 06 18 18" minute var minute = String.Format("{0:m mm}", dt); // "50 50" var secound = String.Format("{0:s ss}", dt); // "23 23" second sec.fraction var fraction = String.Format("{0:f ff fff ffff}", dt); // "2 23 230 2300" var fraction2 = String.Format("{0:F FF FFF FFFF}", dt); // "2 23 23 23" without zeroes A.M. or P.M. var period = String.Format("{0:t tt}", dt); // "P PM" time zone var zone = String.Format("{0:z zz zzz}", dt); // "+0 +00 +00:00" You can use also date separator / (slash) and time sepatator : (colon). For code example For more information MSDN.