This code snippet helps you to understand how to convert a String to a DateTime in C#. We can use the below methods to convert a String to a DateTime in C# easily.
Using DateTime.Parse Method:
using System;
public class ConvertStringtoDateTime
{
public static void Main()
{
string date = "03/04/2019";
try
{
DateTime dateTime = DateTime.Parse(date);
Console.WriteLine("The given date is : " + dateTime);
Console.ReadKey();
}
catch (FormatException)
{
Console.WriteLine("Unable to convert the given date");
}
}
}
Output:
The given date is : 03-04-2019 12:00:00 AM
Using DateTime.TryParse Method:
using System;
public class ConvertStringtoDateTime
{
public static void Main()
{
string date = "03/04/2019";
DateTime dateTime;
if (DateTime.TryParse(date, out dateTime))
{
Console.WriteLine("The given date is :" + dateTime);
}
else
{
Console.WriteLine("Unable to convert the given date");
}
Console.ReadKey();
}
}
Output:
Comments (0)