gpt4 book ai didi

c# - 如何将格式为 "YYYYMM"的字符串转换为 "MMMYY"?

转载 作者:太空宇宙 更新时间:2023-11-03 21:07:47 25 4
gpt4 key购买 nike

我想将 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);
}

...而且,虽然它返回我想要的“9 月 15 日”、“10 月 15 日”等,但我仍然在我的页面上看到“15-Sep”和“10 月 15 日”...?!?

我像这样调用辅助方法:

var monthYearCell = _xlPivotDataSheet.Cells[_lastRowAddedPivotTableData + 1, 4];
monthYearCell.Value2 = ReportRunnerConstsAndUtils.GetMMMYYFromYYYYMM(MonthYear);

我想 Excel 一定是在幕后“自动更正”什么的;让我想起我看过的一部电影(也许是“红军”?)当他的编辑改变他写的内容时,主角变得半弹道。我经常对 Word 和 Excel 有这种感觉。我怎样才能告诉 Excel(假设这是问题所在)不要管它 - “我写的就是我写的”?

最佳答案

你应该使用 DateTime.ParseExact .所以您的代码将如下所示:

internal static string GetMMMYYFromYYYYMM(String YYYYMMVal)
{
DateTime intermediateDate = DateTime.ParseExact(YYYYMMVal, "yyyyMM", CultureInfo.InvariantCulture);

return intermediateDate.ToString("MMMyy");
}

关于c# - 如何将格式为 "YYYYMM"的字符串转换为 "MMMYY"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40045761/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com