你必须在DateTime
对象首先是解析这些值。
例子:
DateTime dt = DateTime.ParseExact("20120321", "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
var result = dt.ToString("yyyy/MM/dd");
其他答案你的意见后编辑: 如果你不喜欢解析,因为它可能会抛出excepations,您可以随时使用TryParse
,像这样:
DateTime dt;
bool success = DateTime.TryParseExact("20120321", "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dt);
if (success)
{
var result = dt.ToString("yyyy/MM/dd");
}
编辑2:使用TryParseExact
多种格式:
DateTime dt;
string[] formats = { "yyyyMMdd", "yyyy" };
bool success = DateTime.TryParseExact("20120321", formats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dt);
if (success)
{
var result = dt.ToString("yyyy/MM/dd");
Console.WriteLine(result);
}
使用2012
作为输入值后,会当使用“20120321”作为输入值产生2012/03/21
,和2012/01/01
。
我现在不能编码答案,但如果你不喜欢DateTime.Parse的答案,我会考虑写一个正则表达式,甚至使用子串。 – row1 2012-03-21 14:55:04
我认为是这样的: Regex.Replace(“20120117”,“(? \ d {4})(? \ d {2})(? \ d {2})”,“$ {y }/$ {m}/$ {d}“) –
row1
2012-03-21 14:58:47
它看起来不像重复 – 2012-03-21 15:04:24