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.
DateTime
object to a string variableTo convert a DateTime
object to a string, we can use the ToString()
method.
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);
In the code above:
DateTime.Now
to get the current time.DateTime
object to a string variable using the ToString()
method.DateTime
object to a string variable in a specific format.DateTime
objectTo convert a string variable to a DateTime
object, we can use the Parse()
and TryParse()
method.
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);
In the code above:
string
type object containing the date value "2023-04-15"
.Parse()
method to convert the string containing the date into the DateTime
object.string
type object containing the time value "12:34 PM"
.Parse()
method to convert the string containing the time into the DateTime
object.string
type object containing the date and time value "2023-04-15 12:34 PM"
.Parse()
method to convert the string into the DateTime
object.DateTime
object.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