Converting a year string i.e. '2005' to a Datetime value

Andy Kirkpatrick picture Andy Kirkpatrick · May 5, 2014 · Viewed 10k times · Source

I am creating a simple input form to create an account. On the form there is an input field for the year the company was founded, this is a simple textbox where the user will type in the year i.e. 2005.

However on attempting to insert this to the database field which is a datetime an error is being thrown despite converting the textbox entry to datetime...

myCompanyAccount.Founded = Convert.ToDateTime(this.TxtCompanyFounded.Text);

Is there a way in which i can can convert a year input i.e. 2005 to a datetime so it can be inserted to the database...? Thanks in advance!

Answer

Soner Gönül picture Soner Gönül · May 5, 2014

It happens just because 2005 is not a standart date and time format and that's the reason Convert.ToDateTime will fail.

You can use DateTime.TryParseExact or DateTime.ParseExact methods instead to parse your custom date and time like;

string s = "2005";
DateTime dt;
if(DateTime.TryParseExact(s, "yyyy", CultureInfo.InvariantCulture,
                          DateTimeStyles.None, out dt))
{
     Console.WriteLine(dt);
}

dt will be 01/01/2005 00:00:00 (of course it's representation depends on your current culture in .ToString() method)

Here a demonstration.