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

标签 c# string datetime composite string.format

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

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

这样结果将取决于 myFormat。

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

我没有成功

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

也不是

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

也不是

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

谢谢大家

最佳答案

你的格式字符串应该是这样的:

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

然后你可以这样格式化:

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

关于c# - 复合字符串格式的 String.Format 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29844514/

相关文章:

c# - 如何以编程方式获取计算机的本地网络 IP 地址?

java - Java中去除字符串中的所有空格并将其转换为数组

java - 如何使用模式中的变量来替换所有除外?

string - 根据日期快速显示标签

sql - 在 Postgresql 上配对顺序事件

C#:在单独的线程上预加载表单

c# - jQuery 属性不起作用

c# - 如何将多个相同的功能类( Controller )组合成一个以数据对象作为参数的类?

javascript - 脚本延迟不起作用

php - 计算两个时间字段之间的差异