Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get DateTime value from DataRow in C#

Tags:

c#

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);
}
like image 655
Santosh Kumar Avatar asked Jul 25 '14 10:07

Santosh Kumar


2 Answers

employeeObject.EmployeeDateOfBirth= Convert.ToDateTime(dr["empDOB"]);
like image 199
Vazgen Torosyan Avatar answered Oct 14 '22 17:10

Vazgen Torosyan


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)
like image 41
Thanos Markou Avatar answered Oct 14 '22 16:10

Thanos Markou