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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
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
1 2 3 |
The given date is : 03-04-2019 12:00:00 AM |
Using DateTime.TryParse Method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
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(); } } |