我是C#的初学者。转换日期格式时遇到困难
我想将日期格式2020-02-02转换为2020年3月2日
我用c#编写了以下函数,但这是很长的代码
c#中是否有任何内置函数可以减少代码
有没有简单的方法可以做到这一点?
public string ConvertToOutputDate(string input) {
// 2020-02-02
string year = input.Substring(0, 4);
string month = input.Substring(5, 2);
string day = input.Substring(8, 2);
string overall = day;
switch (month) {
case("01"):
overall += " Jan";
break;
case ("02"):
overall += " Feb";
break;
case ("03"):
overall += " Mar";
break;
case ("04"):
overall += " Apr";
break;
case ("05"):
overall += " May";
break;
case ("06"):
overall += " Jun";
break;
case ("07"):
overall += " Jul";
break;
case ("08"):
overall += " Aug";
break;
case ("09"):
overall += " Sep";
break;
case ("10"):
overall += " Oct";
break;
case ("11"):
overall += " Nov";
break;
case ("12"):
overall += " Dec";
break;
default:
throw new Exception("> That Month doesn't Exist!: " + month);
}
overall += " " + year;
return overall;
}
}
答案 0 :(得分:1)
您可以使用以下方法简单地转换日期格式:
public string ConvertToOutputDate(string input)
{
return DateTime.Parse(input).ToString("dd MMM yyyy");
}
另外,您还可以通过将其他日期格式作为args传递给ToString()方法来使用它们。
答案 1 :(得分:0)
得到答案
public string ConvertToOutputDate(string input)
{
DateTime date = Convert.ToDateTime(input);
string newDate = date.ToString("dd MMM yyyy");
return newDate;
}