Thursday, 29 May 2014

DateTime String Format in C#

Reference:---http://www.csharp-examples.net/string-format-datetime/

Following examples demonstrate how are the format specifiers rewritten to the output.
DateTime date = new DateTime(2004, 9, 5, 21, 3, 2, 123);
----2004-09-05 21:03:02.123---  = 05-Sep-2004 9:03:02 PM
String.Format("{0:y yy yyy yyyy}", date); // "4 04 004 2004" year String.Format("{0:M MM MMM MMMM}", date); // "9 09 Sep September" month String.Format("{0:d dd ddd dddd}", date); // "5 05 Sun Sunday" day String.Format("{0:h hh H HH}", date); // "9 09 21 21" hour 12/24 String.Format("{0:m mm}", date); // "3 03" minute String.Format("{0:s ss}", date); // "2 02" second String.Format("{0:f ff fff ffff}", date); // "1 12 123 1230" sec.fraction String.Format("{0:F FF FFF FFFF}", date); // "1 12 123 123" without zeroes String.Format("{0:t tt}", date); // "P PM" A.M. or P.M. String.Format("{0:z zz zzz}", date); // "-6 -06 -06:00" time zone
String.Format("{0:d/M/yyyy HH:mm:ss}", date); // "5/9/2004 21:03:02" 
String.Format("{0:d/M/yyyy HH:mm:ss}", date); // "5.9.2004 21:03:02" 
String.Format("{0:M/d/yyyy}", date);            // "9/5/2004"
String.Format("{0:MM/dd/yyyy}", date);          // "09/05/2004"
// day/month names
String.Format("{0:ddd, MMM d, yyyy}", date);    // "Sun, Sep 5, 2004"
String.Format("{0:dddd, MMMM d, yyyy}", date);  // "Sunday, September 5, 2004"
// two/four digit year
String.Format("{0:MM/dd/yy}", date);            // "09/05/04"
String.Format("{0:MM/dd/yyyy}", date);          // "09/05/2004"

Following examples show usage of standard format specifiers in String.Format method and the resulting output.
String.Format("{0:t}", date);  // "9:03 PM"                         
String.Format("{0:d}", date);  // "9/5/2004"                        
String.Format("{0:T}", date);  // "9:03:02 PM"                      L
String.Format("{0:D}", date);  // "Sunday, September 05, 2004"      
String.Format("{0:f}", date);  // "Sunday, September 05, 2004 9:03 PM" 
String.Format("{0:F}", date);  // "Sunday, September 05, 2004 9:03:02 PM" 
String.Format("{0:g}", date);  // "9/5/2004 9:03 PM"             
String.Format("{0:G}", date);  // "9/5/2004 9:03:02 PM"          
String.Format("{0:m}", date);  // "September 05"                  
String.Format("{0:y}", date);  // "September, 2004"                  
String.Format("{0:r}", date);  // "Sun, 05 Sep 2014 21:03:02 GMT"   
String.Format("{0:s}", date);  // "2004-09-05T21:03:02"             
String.Format("{0:u}", date);  // "2004-09-05 21:03:02Z"