How to typecast a DateTime variable in C#
DateTime is a built-in struct provided within the C# language. It is commonly used to store and perform operations related to date and time. It supports many date and time properties, e.g., year, month, day, hour, minute, second, millisecond, day of the week, time of the day, etc. You can read more about the DateTime struct here.
How to convert a DateTime object to a string variable
To convert a DateTime object to a string, we can use the ToString() method.
Code example
Let’s convert a DateTime object to a string using the ToString() method:
DateTime dateTimeObj = DateTime.Now;Console.WriteLine(dateTimeObj);Console.WriteLine(dateTimeObj.GetType());string dateString = dateTimeObj.ToString();Console.WriteLine(dateString);Console.WriteLine(dateString.GetType());string formattedString = dateTimeObj.ToString("yyyy-MM-dd");Console.WriteLine(formattedString);
Explanation
In the code above:
- Line 1: We use
DateTime.Nowto get the current time. - Line 2–3: We print the object along with its type.
- Line 5: We convert the
DateTimeobject to a string variable using theToString()method. - Line 6–7: We print this string containing the date along with its type.
- Line 9: We convert the
DateTimeobject to a string variable in a specific format. - Line 10: We print the new string.
How to convert a string variable to a DateTime object
To convert a string variable to a DateTime object, we can use the Parse() and TryParse() method.
Code example
Let’s convert a string variable to a DateTime object using the Parse() method:
string dateString = "2023-04-15";DateTime dateObject = DateTime.Parse(dateString);Console.WriteLine(dateObject);Console.WriteLine(dateObject.GetType());string timeString = "12:34 PM";DateTime timeObject = DateTime.Parse(timeString);Console.WriteLine(timeObject);string dateTimeString = "2023-04-15 12:34 PM";DateTime dateTimeObject = DateTime.Parse(dateTimeString);Console.WriteLine(dateTimeObject);
Explanation
In the code above:
- Line 1: We initialize the
stringtype object containing the date value"2023-04-15". - Line 2: We use the
Parse()method to convert the string containing the date into theDateTimeobject. - Line 3–4: We print the date object along with its type.
- Line 6: We initialize a
stringtype object containing the time value"12:34 PM". - Line 7: We use the
Parse()method to convert the string containing the time into theDateTimeobject. - Line 8: We print the time object.
- Line 10: We initialize a
stringtype object containing the date and time value"2023-04-15 12:34 PM". - Line 11: We use the
Parse()method to convert the string into theDateTimeobject. - Line 8: We print the
DateTimeobject.
Note:
Parse()can raise error(s) on invalid input. You can handle the error(s) using theTryParse()method. Learn how to useParse()andTryParse()methods here.
Free Resources