Reputation: 2183
Following gives output as 20121212.
DateTime dd = new DateTime(2012, 12, 12);
string val = String.Format("{0:yyyyMMdd}", dd);
And when the format is in a variable. Following does not give above output.
DateTime dd = new DateTime(2012, 12, 12);
string dateFormat = "yyyyMMdd";
string val = String.Format("{0}:{1}", dd, dateFormat);
How can can I achieve it using format in a variable as above?
Upvotes: 5
Views: 14337
Reputation: 465
You can also use .ToString(string format)
DateTime dd = new DateTime(2012, 12, 12);
string strFormat = "yyyyMMdd";
string val = dd.ToString(strFormat);
Upvotes: 0
Reputation: 460038
Just use DateTime.ToString
:
string val = dd.ToString( dateFormat );
You are confusing String.Format
with your format string which does work only in this way {0:yyyyMMdd}
.
Upvotes: 3
Reputation: 98740
Try with String.Format
like this;
DateTime dt = new DateTime(2012, 12, 12);
string Format = "yyyyMMdd";
string yourstring = String.Format("{0:" + Format + "}", dt);
Console.WriteLine(yourstring);
Upvotes: 0
Reputation: 31192
You can use the DateTime.ToString(string) method :
DateTime dd = new DateTime(2012, 12, 12);
string dateFormat = "yyyyMMdd";
string val = dd.ToString(dateFormat);
Upvotes: 0
Reputation: 50104
The simplest way would just be
DateTime dd = new DateTime(2012, 12, 12);
string strFormat = "yyyyMMdd";
string val = dd.ToString(strFormat);
String.Format
doesn't directly support variable format strings.
Upvotes: 2
Reputation: 223207
I believe you have the format in a string variable, May this is what you are looking for:
DateTime dd = new DateTime(2012, 12, 12);
string strFormat = "yyyyMMdd";
string val = String.Format("{0:"+ strFormat + "}", dd);
Upvotes: 3