【发布时间】:2016-10-18 23:01:36
【问题描述】:
我想将 YYYYMM 格式的值(例如“201509”)传递给函数并检索更人性化的“MMMYY”格式,例如“Sep 2015”。
我认为这可能有效:
internal static string GetMMMYYFromYYYYMM(String YYYYMMVal)
{
string intermediateStr = YYYYMMVal + "01";
DateTime intermediateDate = Convert.ToDateTime(intermediateStr);
return intermediateDate.ToString("MMMyy");
}
...但是不,它会因“字符串未被识别为有效日期时间”而崩溃
ISTM 认为 YYYYMMDD 格式应该是可理解的并且可以转换为 DateTime。我需要改变什么?
更新
由于我没有得到我想要的,我决定像这样“暴力破解”:
internal static string GetMMMYYFromYYYYMM(String YYYYMMVal)
{
string yearAsTwoChars = YYYYMMVal.Substring(2, 2);
string threeCharAbbreviation = YYYYMMVal.Substring(4, 2);
if (threeCharAbbreviation.Equals("01"))
{
threeCharAbbreviation = "Jan";
}
else if (threeCharAbbreviation.Equals("02"))
{
threeCharAbbreviation = "Feb";
}
else if (threeCharAbbreviation.Equals("03"))
{
threeCharAbbreviation = "Mar";
}
else if (threeCharAbbreviation.Equals("04"))
{
threeCharAbbreviation = "Apr";
}
else if (threeCharAbbreviation.Equals("05"))
{
threeCharAbbreviation = "May";
}
else if (threeCharAbbreviation.Equals("06"))
{
threeCharAbbreviation = "Jun";
}
else if (threeCharAbbreviation.Equals("07"))
{
threeCharAbbreviation = "Jul";
}
else if (threeCharAbbreviation.Equals("08"))
{
threeCharAbbreviation = "Aug";
}
else if (threeCharAbbreviation.Equals("09"))
{
threeCharAbbreviation = "Sep";
}
else if (threeCharAbbreviation.Equals("10"))
{
threeCharAbbreviation = "Oct";
}
else if (threeCharAbbreviation.Equals("11"))
{
threeCharAbbreviation = "Nov";
}
else if (threeCharAbbreviation.Equals("12"))
{
threeCharAbbreviation = "Dec";
}
return string.Format("{0} {1}", threeCharAbbreviation, yearAsTwoChars);
}
...虽然它返回我想要的“Sep 15”、“Oct-15”等,但我仍然在我的页面上看到“15-Sep”和“Oct-15”...?!?
我这样调用那个辅助方法:
var monthYearCell = _xlPivotDataSheet.Cells[_lastRowAddedPivotTableData + 1, 4];
monthYearCell.Value2 = ReportRunnerConstsAndUtils.GetMMMYYFromYYYYMM(MonthYear);
我认为 Excel 必须在幕后“自动更正”或其他东西;让我想起了我看过的一部电影(也许是“红军”?),当他的编辑改变他写的内容时,主角变得半弹道。我经常对 Word 和 Excel 有这种感觉。我如何告诉 Excel(假设这是问题所在)不要管它——“我写的,我写的”?
【问题讨论】:
-
只要使用
DateTime.ParseExact,你就可以知道它的确切格式。 -
或者使用 DateTime.TryParseExact
标签: c# datetime datetime-format date-conversion