Southlis
»
Forum
»
Asp.net
»
Argument 1: cannot convert from 'System.DateTime?' to 'string'
Rank: Administration
Groups: Administrators
Joined: 12/24/2017(UTC) Posts: 2,811
|
Argument 1: cannot convert from 'System.DateTime?' to 'string'
📌 Nguyên nhân
Bạn đang truyền một biến kiểu DateTime? (nullable DateTime) vào một hàm hoặc thuộc tính yêu cầu string.
Ví dụ gây lỗi:
DateTime? ngaySinh = DateTime.Now; SomeMethod(ngaySinh); // SomeMethod(string value) ✅ Cách sửa 🔹 Cách 1: Chuyển DateTime? sang string
Nếu biến có thể có giá trị:
SomeMethod(ngaySinh?.ToString());
Hoặc định dạng rõ ràng:
SomeMethod(ngaySinh?.ToString("dd/MM/yyyy")); 🔹 Cách 2: Kiểm tra null trước khi dùng if (ngaySinh.HasValue) { SomeMethod(ngaySinh.Value.ToString("dd/MM/yyyy")); } 🔹 Cách 3: Dùng toán tử null-coalescing
Nếu có thể null:
SomeMethod(ngaySinh?.ToString("dd/MM/yyyy") ?? ""); 🔹 Cách 4: Nếu bạn chỉ cần DateTime (không nullable)
Ép kiểu (chỉ dùng khi chắc chắn không null):
SomeMethod(ngaySinh.Value.ToString());
⚠ Nếu ngaySinh = null → sẽ bị lỗi runtime.
📌 Tóm lại
DateTime? ≠ string
Phải dùng .ToString()
Nên kiểm tra null trước khi sử dụng
|
|
|
|
|
|
Rank: Administration
Groups: Administrators
Joined: 12/24/2017(UTC) Posts: 2,811
|
Lỗi xảy ra vì:
@DateTime.Parse(item.CreatedDate)
👉 DateTime.Parse() chỉ nhận string, trong khi item.CreatedDate của bạn nhiều khả năng là DateTime? (nullable DateTime).
Vì vậy mới báo lỗi kiểu:
cannot convert from 'System.DateTime?' to 'string' ✅ Cách sửa đúng 🔹 Trường hợp CreatedDate là DateTime?
Bạn không cần Parse nữa, chỉ cần dùng trực tiếp:
@(item.CreatedDate?.ToString("dd/MM/yyyy hh:mm:ss tt")) 🔹 Nếu muốn xử lý khi null @(item.CreatedDate.HasValue ? item.CreatedDate.Value.ToString("dd/MM/yyyy hh:mm:ss tt") : "")
Hoặc gọn hơn:
@(item.CreatedDate?.ToString("dd/MM/yyyy hh:mm:ss tt") ?? "") ❌ Không nên dùng DateTime.Parse(item.CreatedDate)
Vì:
Parse() dùng khi dữ liệu là string
Còn đây đã là DateTime? rồi
📌 Tóm lại Kiểu dữ liệu Cách dùng string DateTime.Parse(string) DateTime .ToString() DateTime? ?.ToString()
|
|
|
|
|
|
Southlis
»
Forum
»
Asp.net
»
Argument 1: cannot convert from 'System.DateTime?' to 'string'
Forum Jump
You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.