String.Format variable in concatenated string format
I would like to put a variable in a composite format in String.Format. Value
String str = String.Format("{0:[what should I put here]}", mydate, myFormat};
so the result will depend on myFormat.
myFormat = "yyyy" => str = "2015"
myFormat = "hh:mm:ss" => str = "08:20:20"
I failed to complete
String.Format("{0:{1}}", mydate, myFormat}
and
String.Format("{0:{{1}}}", mydate, myFormat}
and
String.Format("{0:\{1\}}", mydate, myFormat}
Thanks everyone.
+3
Kenny
source
to share
2 answers
Your format string should look like this:
string str = "{{0:{0}}}";
Then you can format like this:
string format = string.Format(str, "yyyy");
format = string.Format(format, DateTime.Now); // this will give 2015
+5
Alessandro d'andria
source
to share
If you want to format a date string, it will be much easier for you than your approach:
string myformat = "yyyy";
string secondFormat = "dd.MM.yyyy";
DateTime.Now.ToString(myformat) //2015
DateTime.Now.ToString(secondFormat) //24.04.2015
+3
Marco
source
to share