Abhilash JA Abhilash JA - 23 days ago 17
C# Question

error-cannot convert from 'System.DateTime?' to 'string' C#

Here LogInTime and LogOutTime are datetime datatype. How to convert string format code with respect to Datetime in c#?

LogOutTime and LogInTime both are datetime datatype.

new
{
AccessDate = (DateTime.TryParse(x.LogOutTime, out parsed)) ? parsed.ToShortDateString() : "Unknown",
AccessTimeFrame = (DateTime.TryParse(x.LogOutTime, out parsed)) ? parsed.ToShortTimeString() : "Unknown"
}


Now it occurred error.
"cannot convert from 'System.DateTime?' to 'string'"

Answer

DateTime.TryParse first argument to this method must be of String type, you are passing DateTime object only. Convert x.LogOutTime to String.

Go through this link, MSDN

AccessDate = (DateTime.TryParse(x.LogOutTime.ToString(), out parsed)) ? parsed.ToShortDateString() : "Unknown"

is correct according to me.

Comments