Sunday, September 16, 2012

Error : Year, Month, and Day parameters describe an un-representable DateTime

Error : Year, Month, and Day parameters describe an un-representable DateTime

Well, I had stuck with above error and hardly wasted my half day time.

Solution 1 : You have to check the system date format ( Go to Command prompt type "Date") and SQL server date format (Type select getdate() in the Query window) format, if the system date format differs please change it according to the SQL server format.


Solution 2 : Use the below code format

string dt= DateTime.Now.ToString("MM/dd/yyyy", System.Globalization.DateTimeFormatInfo.InvariantInfo);

And then save the "dt" to the database.
The code is shown below.
       string dt= DateTime.Now.ToString("MM/dd/yyyy", System.Globalization.DateTimeFormatInfo.InvariantInfo);
       Response.Write(dt);
       SqlConnection conn = new SqlConnection("server=.;database=Test;uid=sa;pwd=issac");
       conn.Open();
       SqlCommand cmd = new SqlCommand("insert into test(dtime) values(@dt)", conn);
       cmd.Parameters.Add("@dt", SqlDbType.DateTime);
       cmd.Parameters[0].Value = dt;
       cmd.ExecuteNonQuery();
       conn.Close();
Recommendation (Not in all case, depends) : It would be a good practice to have date selection from the SQL server itself 

1 comment:

  1. Sir, i am getting the same problem in the following sql server 2005 code as "Year, Month, and Day parameters describe an un-representable DateTime"

    The code is :
    DateTime d = new DateTime(DateTime.Today.Year, DateTime.Today.Month - 1, 1);
    DateTime d1 = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1);

    Can you please tell me the exact solution?

    Thanking you.

    ReplyDelete