0

I've been searching but haven't found my answer so forgive me if this question is a duplicate.

I've got a .Net C# application that is using entity framework (EF) to communicate with a SQL Server database. I'm converting a large amount of data and I need to make sure my dates are valid SQL Server datetime types. My POCO classes use a datetime2 type for the dates so a date '0201-04-11 13:00:00 PM' is valid until the insert is actually attempted in the SQL Server database. I was attempting to use DateTime.TryParseExact with something like this...

if (DateTime.TryParseExact(legacyRecord.date_paid.ToString(), "M/d/yyyy hh:mm:ss tt", new CultureInfo("en-us"), DateTimeStyles.None, out datePaid))
{
   // Load record into lease payment table table
   LoadLeasePayment loadLeasePayment = new LoadLeasePayment();
   Decimal LeasePaymentId = loadLeasePayment.AddRecord(prodLeaseId, legacyRecord.amount_paid, datePaid, prodContext, loadDate);
}

I'm sure the solution is obvious but I cannot see the forest for the trees. Any help is much appreciated.

5lb Bass
  • 539
  • 8
  • 15
  • What do you mean by valid? `2017-02-05 18:25:31.998` can be assigned to a datetime but will be changed to `2017-02-05 18:25:31.997` is that a problem? – Martin Smith Feb 05 '17 at 18:27
  • Possible duplicate of [Error - SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM](http://stackoverflow.com/questions/3399061/error-sqldatetime-overflow-must-be-between-1-1-1753-120000-am-and-12-31-999) – Gert Arnold Feb 05 '17 at 22:41

1 Answers1

0

After parsing the string DateTime value, you'll need to verify it is within the range of the target SQL data type. The SqlDateTime structure includes static MinValue and MaxValue fields to facilitate this.

if (DateTime.TryParseExact(legacyRecord.date_paid.ToString(), "M/d/yyyy hh:mm:ss tt", new CultureInfo("en-us"), DateTimeStyles.None, out datePaid))
{
    if((datePaid >= SqlDateTime.MinValue) && (datePaid <= SqlDateTime.MaxValue))
    {
        // Load record into lease payment table table
        LoadLeasePayment loadLeasePayment = new LoadLeasePayment();
        Decimal LeasePaymentId = loadLeasePayment.AddRecord(prodLeaseId, legacyRecord.amount_paid, datePaid, prodContext, loadDate);
    }
}
Dan Guzman
  • 43,250
  • 3
  • 46
  • 71