Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SqlDateTime overflow when inserting value with DateTime.Now

Tags:

c#

sql

linq

Lately I have quite odd error while trying to do db.SubmitChanges():

SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.

The point is, I only use DateTime.Now to set property in my object, and after calling Response.Write(DateTime.Now.ToString()); it shows 17-04-2013 18:03:13 as it should be.

It was not happening earlier, and now the function always breaks. I'm completely clueless - date on my SQL server seems to be ok.

What may cause it?

Edit

I don't think it would help (it just too simple to have any errors IMO), but there's my function:

public bool ReportLogIn(int UserID, string IP, int Succeed ... ) {
    A_UserLoginHistory Report = new A_UserLoginHistory();

    Report.IP = IP;
    Report.UserID = UserID;
    Report.Status = Succeed;
    Report.Date = DateTime.Now; //the only DateTime field
    ...

    try {
        db.A_UserLoginRegistry.InsertOnSubmit(Report);
        db.SubmitChanges();
        return true;
    } catch (Exception e) {
        ErrorLog.AddError(e.ToString());
        return false;
    }
}
like image 267
Lemurr Avatar asked Apr 17 '13 16:04

Lemurr


1 Answers

actually the problem is SQL DateTime =/= C# Datetime

you need to change 2 things

  • Database change the field type from DateTime to DateTime2

  • Query you need to be explicit

    SqlCommand cmd = new SqlCommand("insertsomeDate", conn);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add("@newDate", SqlDbType.DateTime2).Value = yourDate; //<- as example
    

you can find futher informations here,here and here

like image 98
WiiMaxx Avatar answered Sep 29 '22 08:09

WiiMaxx