Original post located at : Convert DateTime string to DateTime variable
In this post I am going to discuss about Conversion of String data in to DateTime.
Problem
For most of the beginner developer they face the problem when "Inserting or Updating" DateTime value in "Database" which is having different presentation of DateTime value than DateTime string entered in UI of Application. For Example DatTime input accept date in format "DD/MM/YYYY" i.e "26/06/2013" so when try to insert this type of DateTime data in DateTime column in database it cause problem and not allow to insert data in Database.
Solution
So to Avoid problem related to during database operation its better to convert DateTime string in DateTime variable i.e. convert entered datetime string value in datetime value. So to do it two thing require to do
1. its better to check in code that string is proper i.e. string is valid Datetime string or not.
2. And convert string of datetime in Database acceptable format to avoid error.
To achieve this in .net provide function called TryParseExact which allows to check the datetime string is valid or not and convertable to DateTime variable.
Example:
string dateTimeString = "28/08/2012";
var date=DateTime.ParseExact(dateTimeString, "dd/MM/yyyy", null).ToString("MM/dd/yyyy");
In above example is conversion take place from "dd/MM/yyyy" to "MM/dd/yyyy".
Note :
Just confirm that the format of the string representation must match the specified format exactly.
Following is code taken from MSDN which shows how this function works for different format.
string[] dates =
{
"31/12/2010",
"12/31/2010",
"1/1/2011",
"1/12/2011",
"12-12-2010",
"12-Dec-10",
"12-December-2010"
};
string[] formattedDates = new string[dates.Length];
string[] formats = { "M/d/yyyy", "d/M/yyyy", "M-d-yyyy",
"d-M-yyyy", "d-MMM-yy", "d-MMMM-yyyy", };
for (int i = 0; i < dates.Length; i++)
{
DateTime date;
if (DateTime.TryParseExact(dates[i], formats,
CultureInfo.InvariantCulture,
DateTimeStyles.None, out date))
formattedDates[i] = date.ToString("dd/MM/yyyy");
}
You take reference of MSDN for creating custom format string. -
Custom Date and Time Format Strings
Conclusion
So by using this function you avoid error of conversion of DateTime string at run-time easily.
Reference :
DateTime.TryParseExact
Leave your comments if you like it.