Creating DateTime from a string in C#

In all the previous tutorials we have used the DateTime structure and used the Today and Now properties which give us the current date and time information. In this tutorial you will learn how to create a DateTime object if you have the date and time information available in a string format. You will need this information when you work with databases. You get the date and time information in the string format from a database and you need to convert it back to the DateTime object. Also when getting date time as user input you need to convert it from string to DateTime object.

Using the DateTime constructor

The first way to create an object of the DateTime structure is to call its constructor and pass it the day, month, year, hour, minute, seconds etc and let it create the object for you. If you look at the DateTime constructor you will see that is has 12 overloads. This means that you can create the object using 12 different methods.

The only problem in using the constructor of the DateTime structure is that you need to pass arguments in the form of days, months, years, hours, minutes and seconds. This means that you need to have values of all these items individually to be able to pass it to the constructor. You cannot ask the user to enter all these values separately, it will become very difficult for him/her. What we are talking here is how to create an object of the DateTime structure when you have the date and time information available in the string format.

Create DateTime object from string

To convert a string representation of the date and time information into the DateTime object you can use the ToDateTime method in the Convert class.

Look at the code below

class Program  {      static void Main(string[] args)      {          string dateTimeInfo = "6/21/2015 18:30:00";          DateTime dt = Convert.ToDateTime(dateTimeInfo);      }  }

Here you see we have the date information in the form of a string. The ToDateTime method in the Convert class gives us the date time object and you can use it in your program to access various pieces of information just like we did with DateTime.Today and DateTime.Now in previous tutorials. Please remember that you need to supply the datetime information in your system’s date and time format. Otherwise during the creation of the DateTime object the Convert.ToDateTime method will throw a FormatException at runtime.

Quick Links



Total Followers
Study Group Created
Study Group Joined
Following Teacher
Following Organization
Blog Articles Added
Questions Asked
Questions Answered
Jobs Posted
Total Members in Group
Questions asked by members
Tasks added in this Group

Please wait..


Login to Open ESchool OR Create your account    Login   SignUp