8

I'm trying to get the date of birth of employees from the DataRows of the DataTable, but I'm getting the exception:

String was not recognized as a valid DateTime.

Please help me to get the value of type DateTime from the DataRow. The following is the my code.

List employeeList = new List();
foreach (DataRow dr in dt.Rows)
{
   DateTime t = DateTime.Now;
   employeeObject.EmployeeID = Convert.ToInt64(dr["empId"]);
   employeeObject.EmployeeFirstName = Convert.ToString(dr["empFirstName"]);
   employeeObject.EmployeeMiddleName = Convert.ToString(dr["empMiddleName"]);
   employeeObject.EmployeeLastName = Convert.ToString(dr["emptLastName"]);
   employeeObject.EmployeeGenderStr = Convert.ToString(dr["empGender"]);
   employeeObject.EmployeeDateOfBirth = Convert.ToDateTime(dr["empDOB"]);
   //employeeObject.EmployeeDateOfBirth = DateTime.ParseExact(dr["empDOB"].ToString().Replace(";", " "), "m/d/yyyy hh:mm:ss", CultureInfo.InvariantCulture);// DateTime.Parse(dr["empDOB"].ToString());
   // employeeObject.EmployeeDateOfBirth = Convert.ToDateTime(dr["empDOB"].ToString().Replace(";", " "), System.Globalization.CultureInfo.GetCultureInfo("hi-IN").DateTimeFormat); ;
   employeeObject.EmployeeContactno = Convert.ToDouble(dr["empContactNo"]);
   employeeObject.EmployeeEmailId = Convert.ToString(dr["empEmailId"]);
   employeeObject.EmployeeAddress = Convert.ToString(dr["empAddress"]);
   employeeObject.EmployeeDesignation = Convert.ToString(dr["empDesgnation"]);
   employeeList.Add(employeeObject);
}
Dave Cousineau
  • 12,154
  • 8
  • 64
  • 80
Santosh Kumar
  • 105
  • 1
  • 2
  • 7
  • 4
    What is the format of the string called `EmployeeDateOfBirth`. I mean what's the format of the value you get form the db. I am asking, because I saw that you use the `String`'s method called `Replace`. If you need to make any replace, you should do this, before the use of `DateTime.ParseExact`. – Christos Jul 25 '14 at 10:21
  • we need an example how the empDOP is stored in db ? – BRAHIM Kamel Jul 25 '14 at 10:21
  • possible duplicate of [Retrieving a DateTime value from a DataRow (C#)](http://stackoverflow.com/questions/1106204/retrieving-a-datetime-value-from-a-datarow-c) – Suji Jul 25 '14 at 10:25
  • Hi thanks for the reply, EmployeeDateOfBirth is of datetime datatype, empDOP is of type datetime datatype – Santosh Kumar Jul 25 '14 at 10:34
  • Well, what I would do besides using the debugger is add a line like `MessageBox.Show(string.Format("{0}: {1}", dr["empDOB"].GetType().Name, (dr["empDOB"] == null ? "NULL" : dr["empDOB"].ToString())));` and post what the MessageBox says. – Dave Cousineau Jul 25 '14 at 11:25

6 Answers6

5
employeeObject.EmployeeDateOfBirth= Convert.ToDateTime(dr["empDOB"]);
Vazgen Torosyan
  • 1,255
  • 1
  • 12
  • 26
4

Try with this and replace "yyyy-MM-dd" with your desired format.

 DateTime.ParseExact(dr["empDOB"].toString(), "dd/MM/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture)
Thanos Markou
  • 2,587
  • 3
  • 25
  • 32
  • What is the logic behind this? – shree.pat18 Jul 25 '14 at 10:23
  • @shree.pat18 What do you mean? – Thanos Markou Jul 25 '14 at 10:30
  • 1
    We don't know what value he gets in emoDB so we can't tell how to parse it. – maszynaz Jul 25 '14 at 10:32
  • @maszynaz Exactly. OP has not provided any info about the date time format or the actual value that he gets when debugging the code, so why would you propose this as an answer? – shree.pat18 Jul 25 '14 at 10:32
  • For some reason i edited my answer exactly after my post saying that he should replace "yyyy-dd-MM" with the his desired format. But christiandev edited it :o – Thanos Markou Jul 25 '14 at 10:35
  • Hi, empDOb is of type DateTime datatype and EmployeeDateOfBirth is also of tyoe datetime datatype – Santosh Kumar Jul 25 '14 at 10:36
  • @Thanos Markou the olution which you have given showing error that DateTime.TryParseExcet nooverload methods doesnot accept 3 Parameters – Santosh Kumar Jul 25 '14 at 10:42
  • @SantoshKumar Try again. – Thanos Markou Jul 25 '14 at 10:48
  • @ThanosMarkou, I edited the post to wrap the *one liner* onto a second line to make it easier to read than having to scroll! – Christian Phillips Jul 25 '14 at 10:51
  • @Thanos Markou I am getting exception "String was not recognized as a valid DateTime." DataRow value for DoB is '1/1/1990 11:20:30 AM' – Santosh Kumar Jul 25 '14 at 10:57
  • @Thanos Markou I am getting exception "String was not recognized as a valid DateTime." for DateTime.ParseExact(dr["empDOB"].toString(), "dd/MM/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture). Hi dr["empDOB"] contains the value of like '1/1/1990 11:20:30 AM' i want to take this value and assign to the object employeeObject.EmployeeDateOfBirth – Santosh Kumar Jul 25 '14 at 11:09
  • @Thanos Markou Its working now thanks for the reply, I am struggling to solve this issue since morning(Hyderabad,INDIA). Once again thank u – Santosh Kumar Jul 25 '14 at 11:25
3

You could use:

employeeObject.EmployeeDateOfBirth = dr["empDOB"] != null ? 
         (DateTime)dr["empDOB"] : 
          DateTime.MinValue;

This will give you the MinValue if it's null.

Christian Phillips
  • 18,399
  • 8
  • 53
  • 82
  • Hi, Thanks for the reply, it throwing the exception like "Specified cast is not valid." dr["empDOB"] contains the value of like '1/1/1990 11:20:30 AM' i want to tke this value and assign to the object employeeObject.EmployeeDateOfBirth – Santosh Kumar Jul 25 '14 at 11:05
  • 1
    @SantoshKumar Can you put a BreakPoint on the line and see what value is actually in `dr["empDOB"]`? Are you sure that it's a `DateTime` value, as you said? If it really is a `DateTime`, you shouldn't get an `InvalidCastException`. (I wonder if it could have something to do with `DBNull` rather than `null`?) – Dave Cousineau Jul 25 '14 at 11:07
  • @Sahuagin Hi, dr["empDOB"] contains the value of like '1/1/1990 11:20:30 AM' i want to take this value and assign to the object employeeObject.EmployeeDateOfBirth – Santosh Kumar Jul 25 '14 at 11:11
  • what datatype is it in the database? (I'm assuming you're getting the data from a DB) – Christian Phillips Jul 25 '14 at 11:59
  • This sould be the accepted answer. But it sould check for DbNull.Value, because database null values are DbNull-s by the framework. I can't see why are here so many complicated answers out there. If is's a DateTime, treat it as a DateTime. – CLS Oct 22 '20 at 21:11
1

Check for null before binding.

From what I can see, am not seeing any check for null and replacing the null with datetime minValue, unless the check is been done within your DB?. I had a similar problem, and that check resolved it.

if (!string.IsNullOrEmpty(dr["empDOB"])) {employeeObject.EmployeeDateOfBirth = Convert.ToDateTime(dr["empDOB"]);

} else { DateTime DOB = DateTime.MinValue;}

kachidude
  • 31
  • 1
  • 5
  • Hi, Thanks for the reply but DateTime datatype will not have any nulls, it will have min value DateTime.MinValue....and min value is 1/1/1900 00:00:00 as my datatbase table column datatype is DateTime if null value is passed it will take Date.Min value . – Santosh Kumar Jul 25 '14 at 10:46
  • @kachide Hi, db doesnot have anu null value it contains value 1/1/1990 11::20:00, but it causing the issue – Santosh Kumar Jul 25 '14 at 11:17
  • @ kachidude thanks for reply its working now with following solutionemployeeObject.EmployeeDateOfBirth = DateTime.ParseExact(dr["empDOB"].ToString(), "d/M/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture); – Santosh Kumar Jul 25 '14 at 11:29
1

It's a little late, but if someone needs it, try this simple solution.

foreach (DataRow row in dt.Rows)
{
   if (row["empDOB"] != DBNull.Value)
      item.vytvorena = (DateTime)row["empDOB"];
}
0

Try this:

employeeObject.EmployeeDateOfBirth = DateTime.ParseExact(dr["empDOB"].toString(), 
"d/M/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
maszynaz
  • 309
  • 4
  • 11
  • Hi, Thanks for the reply, it throwing the exception like "Specified cast is not valid." dr["empDOB"] contains the value of like '1/1/1990 11:20:30 AM' i want to tke this value and assign to the object employeeObject.EmployeeDateOfBirth – Santosh Kumar Jul 25 '14 at 11:01