C#.Net convert date to string and string formatting

It’s very easy to convert date time to string in C#.Net. To convert DateTime into string you can use String.Format function in C# ASP.Net. And to convert string into DateTime you can use Convert.ToDateTime function this post will show how to do this conversion.

If you have Date Time value in the Data table and want to convert that to string? use below example.

string s = string.Empty;
s = String.Format(“{0:yyyyMMdd}”, dt.Rows[i][“DateTimeValue”]);

The following list is the most commonly used format characters in C#.Net

d – Numeric day of the month without a leading zero.
dd – Numeric day of the month with a leading zero.
ddd – Abbreviated name of the day of the week.
dddd – Full name of the day of the week.

m – Minutes with no leading zero.
mm – Minutes with leading zero.

M – Numeric month with no leading zero.
MM – Numeric month with a leading zero.
MMM – Abbreviated name of month.
MMMM – Full month name.

h – 12 Hour clock, no leading zero.
hh – 12 Hour clock with leading zero.
H – 24 Hour clock, no leading zero.
HH – 24 Hour clock with leading zero.

s – Seconds with no leading zero.
ss – Seconds with leading zero.

t – AM/PM but only the first letter.
tt – AM/PM ( a.m. / p.m.)

y – Year with out century and leading zero.
yy – Year with out century, with leading zero.
yyyy – Year with century.

zz – Time zone off set with +/-.

Below examples shows how are the above listed format specifiers rewritten the result.

//Create date time 1984-06-01 11:09:01

String.Format(“{0:M MM MMM MMMM}”, dt); // Result : 6 06 Jun June
String.Format(“{0:y yy yyy yyyy}”, dt); // Result : 84 84 1984 1984
String.Format(“{0:d dd ddd dddd}”, dt); // Result : 1 01 Fri Friday
String.Format(“{0:s ss}”, dt); // Result : 1 01
String.Format(“{0:t tt}”, dt); // Result : A AM
String.Format(“{0:z zz zzz}”, dt); // Result : +8 +08 +08:00
String.Format(“{0:h hh H HH}”, dt); // Result : 11 11 11 11
String.Format(“{0:m mm}”, dt); // Result : 9 09

Leave a Reply

Your email address will not be published. Required fields are marked *

(Required)

Proudly powered by WordPress   Premium Style Theme by www.gopiplus.com