Sabari M Sabari M
Updated date Feb 22, 2021
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.

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:

 

ABOUT THE AUTHOR

Sabari M
Sabari M
Software Professional, India

IT professional with 14+ years of experience in Microsoft Technologies with a strong base in Microsoft .NET (C#.Net, ASP.Net MVC, ASP.NET WEB API, Webservices,...Read More

https://www.techieclues.com/profile/alagu-mano-sabari-m

Comments (0)

There are no comments. Be the first to comment!!!