Tuesday 22 January 2013

String Format for Int [C#]

Solutions 1:  
Add zeroes before number
String.Format("{0:00000}", 15);          // "00015"
String.Format("{0:00000}", -15);         // "-00015"

Align number to the right or left
String.Format("{0,5}", 15);              // "   15"
String.Format("{0,-5}", 15);             // "15   "
String.Format("{0,5:000}", 15);          // "  015"
String.Format("{0,-5:000}", 15);         // "015  "

Different formatting for negative numbers and zero
String.Format("{0:#;minus #}", 15);      // "15"
String.Format("{0:#;minus #}", -15);     // "minus 15"
String.Format("{0:#;minus #;zero}", 0);  // "zero"


Custom number formatting (e.g. phone number)
tring.Format("{0:+### ### ### ###}", 447900123456); // "+447 900 123 456"
String.Format("{0:##-####-####}", 8958712551);       // "89-5871-2551"

String to Date to String in C#


Solutions 1:  

String to Date

DateTime Date = Convert.ToDateTime("1/22/2013 12:37:45 PM");

Date to String 

MessageBox.Show(Date.ToString("d"));    //     1/22/2013                 
MessageBox.Show(Date.ToString("D"));    //    Tuesday, January 22, 2013
MessageBox.Show(Date.ToString("U"));     //    Tuesday, January 22, 2013 12:37:45 PM
MessageBox.Show(Date.ToString("y"));    //    January, 2013
MessageBox.Show(String.Format("{0:ddd}",Date));  //Tue

MessageBox.Show(String.Format("{0:MM/dd/yyyy}",Date));  // 01/22/2013


String Format for DateTime [C#]