Replace out of range date with null
<p>I'm reading in utility billing information from an EDI file which contains reading start and end dates, amongst other things.</p>

<p>Before I write my various records to my database I am taking the EDI object and transforming it into my database model using the following method:</p>

<pre><code>var invoices = EdiReader.EdiReader.ReadEdiAndConvert(filePath);    
var invoicesForSite = invoices.Where(x =&gt; x.SiteNo == site);    
List&lt;DbBillInvoice&gt; dbBillInvoices = new List&lt;DbBillInvoice&gt;();

    foreach (var invoice in invoicesForSite)
       {
          var newInvoice = new DbBillInvoice()
          {
            ...
            MeterNumber = invoice.MeterNumber,
            StartReadDate = invoice.StartReadDate,
            StartRead = invoice.StartRead,
            StartReadType = invoice.StartReadType,
            EndReadDate = invoice.EndReadDate,
            EndRead = invoice.EndRead,
            EndReadType = invoice.EndReadType,
            ...
          };

            dbBillInvoices.Add(newInvoice);
       }    
            return nPowerBillInvoices;
</code></pre>

<p>In the EDI file format, it seems records that shouldn't have a <code>StartReadDate</code> or <code>EndReadDate</code> are coming in as <code>{01/01/0001 00:00:00}</code> rather than null, then when I try to do the write to the table I receive the following:</p>

<blockquote>
  <p>The conversion of a datetime2 data type to a datetime data type
  resulted in an out-of-range value.</p>
</blockquote>

<p>I think this is because the default and lowest value for <code>DateTime</code> is <code>1/1/0001 12:00:00 AM</code></p>

<p>I've made the two date properties nullable now however I need to somehow convert these properties to be null rather than what they come in as when the date is not something meaningful.</p>

<p>I have tried doing the following:</p>

<pre><code>StartReadDate = billInvoice.StartReadDate == default(DateTime) 
  ? null 
  : billInvoice.StartReadDate;
</code></pre>

<p>However I soon realised that the default DateTime value in .Net is 12 hours ahead of this EDI value so nothing matches this condition.</p>

<p><strong>How can I capture these bad dates and replace them with null</strong></p>