将此自定义字符串格式转换为DateTime?

时间:2011-12-06 04:53:14

标签: c# string datetime

如何转换以下字符串

    09/11/2011 9:40:55 pm
    20/11/2011 3:40:55 am

进入C#DateTime?

3 个答案:

答案 0 :(得分:11)

使用DateTime.ParseExact

string dateString = "20/11/2011 3:40:55 am";
DateTime parsedDate = DateTime.ParseExact(
   dateString,
   "dd/MM/yyyy h:mm:ss tt",
   CultureInfo.InvariantCulture);

答案 1 :(得分:-1)

DateTime.Parse:

http://msdn.microsoft.com/en-us/library/1k1skd40.aspx

另见:

http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.timeseparator.aspx

http://msdn.microsoft.com/en-us/library/system.datetime.aspx

例如:

string dateString = "5/1/2008 8:30:52 AM";
DateTime date1 = DateTime.Parse(dateString, 
                          System.Globalization.CultureInfo.InvariantCulture); 

答案 2 :(得分:-2)

DateTime DT_1 = new DateTime(2011, 11, 9, 21, 40, 55);
DateTime DT_2 = new DateTime(2011, 11, 20, 15, 40, 55);