复合字符串格式的String.Format变量

时间:2015-04-24 09:59:49

标签: c# string datetime composite string.format

我想在String.Format中将变量放入复合格式。含义

// Write the buffer into a file.
writeBuffer(buffer, "D:\\test.xml");
// Parse the file into a DataSet.
IDataSet test = createDataSet("D:\\test.xml");

// Cast the StringBuffer into an InputSource and give it to
// a FlatXMLDataSetBuider.
InputSource xmlInputStream = new InputSource(buffer.toString());

FlatXmlDataSetBuilder flatXmlBuilder = new FlatXmlDataSetBuilder();
flatXmlBuilder.setColumnSensing(true); // We do not have a dtd to give.
IDataSet dataSet = flatXmlBuilder.build(xmlInputStream); // Error is thrown here

private static void writeBuffer(StringBuffer buffer, String path)
{
    try
    {
        String content = buffer.toString();

        File file = new File(path);

        // if file doesnt exists, then create it
        if (!file.exists())
        {
            file.createNewFile();
        }

        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(content);
        bw.close();
    }
    catch (Exception e)
    {

    }
}

private static IDataSet createDataSet(String filePath)
{
    IDataSet dataSet = null;
    try
    {
        InputStream is = new FileInputStream(filePath);
        InputSource xmlInputStream = new InputSource(is);

        FlatXmlDataSetBuilder builder = new FlatXmlDataSetBuilder();
        builder.setColumnSensing(true);
        dataSet = builder.build(xmlInputStream);
    }
    catch (Exception e)
    {

    }
    return dataSet;
}

因此结果将取决于myFormat。

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

我没有用

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

也不是

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

也不是

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

谢谢大家。

2 个答案:

答案 0 :(得分:5)

您的格式字符串应该是:

string str = "{{0:{0}}}";

然后你可以像这样格式化:

string format = string.Format(str, "yyyy");
format = string.Format(format, DateTime.Now); // this will give 2015

答案 1 :(得分:3)

如果您想格式化日期字符串,那么确保您的方法更容易:

string myformat = "yyyy";
string secondFormat = "dd.MM.yyyy";
DateTime.Now.ToString(myformat) //2015
DateTime.Now.ToString(secondFormat) //24.04.2015