Welcome Guest! To enable all features please Login or Register.

Notification

Icon
Error

Options
Go to last post Go to first unread
admin  
#1 Posted : Saturday, February 28, 2026 11:03:14 AM(UTC)
admin

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
admin  
#2 Posted : Saturday, February 28, 2026 11:04:15 AM(UTC)
admin

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()
Users browsing this topic
Guest (7)
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.