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

时间:2011-01-17 10:51:30

标签: c# datetime datetime-format

我想将包含yyyyMMdd格式的日期的字符串转换为mm-dd-yyyy DateTime格式。我怎么得到它?

3 个答案:

答案 0 :(得分:46)

var dateString = "20050802";
var date = myDate = DateTime.ParseExact(dateString,
                                    "yyyyMMdd",
                                    System.Globalization.CultureInfo.InvariantCulture);

善。

答案 1 :(得分:3)

public static DateTime ConvertDate(string date, string pattern)
{
    DateTime retval = DateTime.MinValue;
    if (System.DateTime.TryParseExact(date, pattern, System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out retval))
       return retval;

    // Could not convert date..
    return DateTime.MinValue;
}


DateTime myDate = ConvertDate("20101230", "yyyyMMdd");

答案 2 :(得分:1)

CultureInfo provider = CultureInfo.CreateSpecificCulture("en-UK");   

string dateString = "19850121"; //in yyyyMMdd format 

string oldFormat = "yyyyMMdd"; 

DateTime result = DateTime.ParseExact(dateString, oldFormat, provider); //MM/dd/yyyyformat