C# String.Format - Feed in custom format

John Bustos

I'm wondering if this is possible and, if so, how to accomplish it.

I know that the String.Format function allows you to specify a format for a parameter as follows, for example:

String.Format("The Date is {0:yyyy-MM-dd}", DateTime.Now);

But I wanted to know the best way to feed in the desired format (for exmaple "yyyy-MM-dd") to end up with a function that would work as follows (does not work, but shows what I'm trying to accomplish):

static string CreateFileName(string filename, string DateTimeFormat = "yyyy-MM-dd")
{
    return String.Format("{0} - {1:{2}}", filename, DateTime.Now, DateTimeFormat);
}

I'm supposing I could put in a fake place holder and do a String.Replace first:

string formatString = "{0} - {1:{FMT}}";
formatString = formatString.Replace("{FMT}", DateTimeFormat);

But I'm curious to know if there is a better way to accomplish what I'm trying to do.

Thanks!!

William Moore

You could use:

var format = "yyyy-MM-dd";
var dateTimeString = string.Format("{0}", DateTime.Now.ToString(format));

So your function would become:

static string CreateFileName(string filename, string DateTimeFormat = "yyyy-MM-dd")
{
    return String.Format("{0} - {1}", filename, DateTime.Now.ToString(DateTimeFormat));
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related