如何以" YYYYMM"格式转换字符串?到" MMMYY"?

时间:2016-10-14 14:34:06

标签: c# datetime datetime-format date-conversion

我希望以YYYYMM格式传递值,例如" 201509"一个功能和检索人类友好的" MMMYY"格式,例如" 2015年9月"。

我认为这可行:

internal static string GetMMMYYFromYYYYMM(String YYYYMMVal)
{
    string intermediateStr = YYYYMMVal + "01";
    DateTime intermediateDate = Convert.ToDateTime(intermediateStr);
    return intermediateDate.ToString("MMMyy");
}

...但是没有,它与" 字符串崩溃没有被识别为有效的DateTime "

ISTM,YYYYMMDD格式应该是grokkable并且可以转换为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日和#34;," 10月15日"等等,我仍然看到" 15-Sep"和" 10月15日"在我的页面上......?!?

我正在调用这样的辅助方法:

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

我认为Excel必须是"自动修正"幕后的东西;让我想起了我看过的一部电影(" Reds"也许?),当他的编辑改变了他所写的内容时,主角变成了半弹道。我常常对Word和Excel有这种感觉。我怎么能告诉Excel(假设这是问题)只是不管它 - "我写了什么,我写了"?

3 个答案:

答案 0 :(得分:4)

您应该使用DateTime.ParseExact。所以你的代码看起来像这样:

void foo()
/** {this does something **/
{ baz(); }

答案 1 :(得分:1)

您可以使用switch-case代替所有if-else块,这样可以增加可读性。即。

switch (threeCharAbbreviation)
{
    case "01":
        threeCharAbbreviation = "Jan";
        break;
    case "02":
        //Etc.
    default:
        break;
}

您可以在Excel中明确设置单元格的格式。没有自己测试过,但你可以尝试下面的示例代码:

Excel.Range formatRange;
formatRange = xlWorkSheet.Range["A3", "B4"];
formatRange.NumberFormat = "MM-YY";

答案 2 :(得分:-1)

试试这个

return DateTime.ParseExact(intermediateDate.ToString(), "yyyyMM", CultureInfo.InvariantCulture).ToString();