Convert.ToDateTime() chuyển đổi giá trị (thường là chuỗi) thành DateTime. Xử lý an toàn null (trả về DateTime.MinValue).
Ví dụ minh họa
using System;
public class Demo
{
public static void Main()
{
string myDateString = "09/09/2018";
DateTime result = Convert.ToDateTime(myDateString);
Console.WriteLine("'{0}' chuyển thành {1}", myDateString, result);
}
}
Kết quả đầu ra
'09/09/2018' chuyển thành 9/9/2018 12:00:00 AM
Lưu ý:
- Phân tích chuỗi theo culture hiện tại (CurrentCulture)
- Chuỗi không hợp lệ ném
FormatException - Dùng
DateTime.ParseExact()hoặcTryParseExact()để kiểm soát format chính xác - Null →
DateTime.MinValue(01/01/0001 00:00:00)