I am trying to check if the DateTime
variables "starttime"
and "endtime"
have null
values and then trying to initialize to an empty
value as below, but I'm running into below compilation errors. What is the best way to achieve this?
string htmllink = "";
DateTime? starttime = null;
DateTime? endtime = null;
htmllink = (dbNullCheck.isColumnNull(rdr, "html_link")) ? "" : rdr.GetString(3);
starttime = (dbNullCheck.isColumnNull(rdr, "start_time")) ? "" : rdr.GetString(4);
endtime = (dbNullCheck.isColumnNull(rdr, "end_time")) ? "" : rdr.GetString(5);
results.htmllist.Add(new gethtmllist() { resulthtmllink = htmllink,
duration = (starttime - endtime).ToString() });
Error:
Error 2 Cannot implicitly convert type 'string' to 'System.DateTime?'
UPDATE:-
string htmllink = "";
htmllink = (dbNullCheck.isColumnNull(rdr, "html_link")) ? "" : rdr.GetString(3);
DateTime? starttime = (dbNullCheck.isColumnNull(rdr, "start_time")) ? new DateTime() : rdr.GetDateTime(4);
DateTime? endtime = (dbNullCheck.isColumnNull(rdr, "end_time")) ? new DateTime() : rdr.GetDateTime(5);
results.htmllist.Add(new gethtmllist()
{
resulthtmllink = htmllink,
duration = starttime.HasValue && endtime.HasValue ? (endtime.Value - starttime.Value).ToString() : ""
});
I try an string.Empty to test:starttime = string.IsNullOrEmpty(str) ? (DateTime?)null : DateTime.Now;
It is successed. So your code could be:
starttime = (dbNullCheck.isColumnNull(rdr, "start_time")) ? (DateTime?)null : rdr.GetDateTime(4);
endtime = (dbNullCheck.isColumnNull(rdr, "end_time")) ? (DateTime?)null: rdr.GetDateTime(5);
Update 1: .Net Fiddle example for string.Empty: Link
You can't set dates to a string
starttime = (dbNullCheck.isColumnNull(rdr, "start_time")) ? "" : rdr.GetString(4);
endtime = (dbNullCheck.isColumnNull(rdr, "end_time")) ? "" : rdr.GetString(5);
should be
starttime = (dbNullCheck.isColumnNull(rdr, "start_time")) ? new DateTime() : rdr.GetDateTime(4);
endtime = (dbNullCheck.isColumnNull(rdr, "end_time")) ? new DateTime() : rdr.GetDateTime(5);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With