Search code examples
c#stringdatetimecompositestring.format

String.Format variable in composite string format


I would like to put a variable into composite format in String.Format. Meaning

String str = String.Format("{0:[what should I put here]}", mydate, myFormat};

so that the result will depend on myFormat.

myFormat = "yyyy" => str = "2015"
myFormat = "hh:mm:ss" => str = "08:20:20"

I did not suceed with

String.Format("{0:{1}}", mydate, myFormat}

nor

String.Format("{0:{{1}}}", mydate, myFormat}

nor

String.Format("{0:\{1\}}", mydate, myFormat}

Thanks everyone.


Solution

  • Your format string should be like:

    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