Click here to Skip to main content
15,886,840 members
Articles / Database Development
Tip/Trick

Convert DateTime string to DateTime variable

Rate me:
Please Sign up or sign in to vote.
3.00/5 (1 vote)
12 Dec 2012CPOL1 min read 37.1K   6   2
Convert DateTime string to DateTime variable

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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India

Microsoft C# MVP (12-13)



Hey, I am Pranay Rana, working as a Team Leadin MNC. Web development in Asp.Net with C# and MS sql server are the experience tools that I have had for the past 5.5 years now.

For me def. of programming is : Programming is something that you do once and that get used by multiple for many years

You can visit my blog


StackOverFlow - http://stackoverflow.com/users/314488/pranay
My CV :- http://careers.stackoverflow.com/pranayamr

Awards:



Comments and Discussions

 
GeneralMy vote of 3 Pin
Klaus Luedenscheidt13-Dec-12 19:08
Klaus Luedenscheidt13-Dec-12 19:08 
QuestionLocal or UTC / Issue with multiple formats Pin
Robert Slaney13-Dec-12 18:25
Robert Slaney13-Dec-12 18:25 
Always use DateTimeStyles to explicitly state whether the DateTime is local or UTC, otherwise the DateTime's Kind value will be Unspecified.

Also, if you specified multiple formats that can be ambiguous you will inconsistent behaviour

C#
DateTime.ParseExact("12/01/2012", new string[] { "MM/dd/yyyy", "dd/MM/yyyy" }, CultureInfo.CurrentCulture, DateTimeStyles.AssumeUniversal).Month = 12
DateTime.ParseExact("13/01/2012", new string[] { "MM/dd/yyyy", "dd/MM/yyyy" }, CultureInfo.CurrentCulture, DateTimeStyles.AssumeUniversal).Month = 1


My advice, always use standard unambiguous date format - yyyy/MM/dd, and ALWAYS use UTC dates and convert to their locale when displaying dates.

modified 14-Dec-12 0:34am.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.