How to convert Year to DateTime object in C# .Net

Last Reply on Dec 30, 2014 04:47 AM By Mudassar

Posted on Dec 30, 2014 04:45 AM

String was not recognized as a valid DateTime.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.FormatException: String was not recognized as a valid DateTime.

Source Error:

Line 122:                                string contentType = file.ContentType;
Line 123:                                int CompID = Convert.ToInt32(ddl_companyNameForuploadInComing.SelectedItem.Value);
Line 124:                                DateTime InComingYear = Convert.ToDateTime(ddl_yearOfInComing.SelectedItem.Value);
Line 125:                                byte[] fileData = new byte[size];
Line 126:                                file.InputStream.Read(fileData, 0, size);

error in this line:

DateTime InComingYear = Convert.ToDateTime(ddl_yearOfInComing.SelectedItem.Value);

I am using drop down list to show years only

Posted on Dec 30, 2014 04:47 AM

A year value cannot be converted to DateTime. You also need to pass month and day and hence do in following way

DateTime dt = new DateTime(int.Parse(ddl_yearOfInComing.SelectedItem.Value), 1, 1);

Or use Integer field to ssave year values