Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize an empty value to a datetime variable?

Tags:

c#

asp.net

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() : ""
                });
like image 500
dot net Avatar asked Apr 29 '17 00:04

dot net


2 Answers

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

like image 165
is_oz Avatar answered Sep 28 '22 02:09

is_oz


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);
like image 21
chris-crush-code Avatar answered Sep 28 '22 02:09

chris-crush-code