2010-09-23 62 views

Trả lời

39

Hãy thử sử dụng DateTime.ParseExact:

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

Xem Parsing Date and TimeDateTime.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); 
} 

Prints:

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

cụ thể hơn, 'DateTime.ParseExact()' – Mark

+2

Bạn cũng có thể sử dụng 'TryParseExact()' thay vì bắt ngoại lệ. –

1

Bạn có thể làm điều này rất dễ dàng.

Đây là ví dụ.

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>"); 
    } 
Các vấn đề liên quan