Abhilash JA Abhilash JA - 1 year ago 103
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.

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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download