How to initialize an empty value to a datetime variable?

asp.net, c#

Solution

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

Problem

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() : "" }); ```

Original source

Related problems