将ddMMyyyy格式的字符串转换为DateTime类型

22

如何将ddMMyyyy格式的字符串转换为DateTime?

3个回答

45

建议使用DateTime.ParseExact函数进行解析:

DateTime.ParseExact(yourDateString, "ddMMyyyy", CultureInfo.InvariantCulture);

3

请参阅日期和时间解析DateTime.ParseExact()

String dateString = "15072008";
String format = "ddMMyyyy";
try {
   DateTime result = DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture);
   Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException) {
   Console.WriteLine("{0} is not in the correct format.", dateString);
}

输出:

15072008 converts to 7/15/2008 12:00:00 AM.

1
更具体地说,DateTime.ParseExact() - Mark
2
你也可以使用TryParseExact()而不是捕获异常。 - Callum Rogers

1
你可以很容易地做到这一点。
这是一个示例。
    String origionalDate = "12/20/2013"; // Format : MM/dd/yyyy
    string origionalFormat = "MM/dd/yyyy";
    string convertInToFormat="dd/MM/yyyy";
    String convertedDate;
    DateTime objDT;

    if (DateTime.TryParseExact(origionalDate, origionalFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out objDT) == true)
    {
        convertedDate = objDT.ToString(convertInToFormat);
        Response.Write("<b>Original DateTime Format ( " + origionalFormat + " ) : </b>" + origionalDate);
        Response.Write("<br/>");
        Response.Write("<b>Converted DateTime Format ( " + convertInToFormat + " )  : </b>" + convertedDate);
    }
    else
    {
        Response.Write("<b>Not able to parse datetime.</b>");
    }

相反的情况呢? - 3 rules

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接