Convert String to DateTime

InterServer Web Hosting and VPS

Convert String to DateTime

Here we'll look at a way of converting a String into a DateTime object in C#. (.NET 2.0)

You may have a string value of a date, (for instance from a TextBox) and you need to convert that string into a DateTime (so you can compare dates for instance).

One way you can do this is to use the Convert.ToDateTime(string value). However, this isn't really the best way unless you can ensure the format of your string. For instance, if your string should end up containing invalid values such as 'Hello' then an exception will be thrown and we don't really want to cause exceptions. If you do use this approach, validate your string value before passing it to be converted. So use the following example with caution:

// take a string containing a datetime value
// ensure you have validated your string value as in a DateTime format
string _date = @"15/09/2008";

// attempt to convert, potential to cause an exception
DateTime _convertDate = Convert.ToDateTime(_date);

Another way to approach this is with the DateTime.TryParse(string _date, out DateTime _convertedDate) method. You need to create the _convertedDate DateTime object first, as it's value is created in the DateTime.TryParse and passed as as output parameter. If the attempt to parse the string into a datetime value fails, then the DateTime value will be set to DateTime.MinValue, and an exception will not be thrown in the application. So all you need to do is check that the DateTime has a value of greater than DateTime.MinValue, or use a boolean to carry out the DateTime.TryParse method and the boolean will return true or false, true for a successful conversion, or false for a failed conversion.

// create our objects
DateTime _startDate = DateTime.MinValue;
string _startDateString = @"21/03/2007";

// attempt the parsing
DateTime.TryParse(_startDateString, out _startDate);

// Check the parsing worked
if (_startDate > DateTime.MinValue)
   // carry on actions

Or, as mentioned above you can use a boolean to assess the conversion:

// create our objects
DateTime _startDate = DateTime.MinValue;
string _startDateString = @"28/08/2011";

// attempt the parse and record success of conversion in a boolean
bool _didDateConvert = DateTime.TryParse(_startDateString, out _startDate);

Note how we use literal strings to store the date formatting in the string and prevent them acting as escape characters.

Sponsored Links
SolarSystem - AngularJS Demo
SolarSystem - Angular JS Demo

Check out my first Angular JS demo hosted in Azure, it helped win my first Angular contract. Put the sound on.