简体   繁体   English

如何将日期格式从 yyyy-mm-dd 转换为 dd MMM yyyy

[英]How to convert date format from yyyy-mm-dd to dd MMM yyyy

I'm a beginner in C#.I'm facing difficulty in converting date format我是 C# 的初学者。我在转换日期格式时遇到了困难

I want to convert the date format 2020-02-02 to 02 Mar 2020我想将日期格式 2020-02-02 转换为 2020 年 3 月 2 日

I wrote the below function in c#,but it is very lengthy code我用c#写了下面的函数,但是代码很长

Is there any built-in function available in c# to reduce code c#中是否有任何可用的内置函数来减少代码

Is there a simple way to do this?有没有一种简单的方法可以做到这一点?

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;
}
}

You can use the following method to convert date format simply:您可以使用以下方法简单地转换日期格式:

public string ConvertToOutputDate(string input)
{
         return DateTime.Parse(input).ToString("dd MMM yyyy");
}

And also you can play with other date formats by passing them as args to ToString() method.您还可以通过将它们作为参数传递给 ToString() 方法来使用其他日期格式。

Got the Answer得到答案

public string ConvertToOutputDate(string input)
        {
            DateTime date = Convert.ToDateTime(input);
            string newDate = date.ToString("dd MMM yyyy");
            return newDate;
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM