Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format date using variable

Tags:

c#

date-format

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?

like image 938
mrd Avatar asked Jan 08 '13 10:01

mrd


People also ask

How do I change the format of a date variable?

From the Variable Manager -> Show System Variable -> Data-Time -> In front of the date click on ... button -> Select the format.

How do I format a date and time in a variable?

Just use DateTime. ToString : string val = dd. ToString( dateFormat );

How do you assign a date to a variable value?

Assigned TagsString s = "09/22/2006"; SimpleDateFormat sd = new SimpleDateFormat("MM/dd/yyyy"); Date date1 = sd. parse(s); Calendar c = Calendar. getInstance(); c. set(2006, 8, 22); //month is zero based Date date2 = c.


2 Answers

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);
like image 123
Habib Avatar answered Oct 02 '22 22:10

Habib


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}.

like image 45
Tim Schmelter Avatar answered Oct 02 '22 21:10

Tim Schmelter