TechieClues TechieClues
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

TechieClues
TechieClues

I specialize in creating and sharing insightful content encompassing various programming languages and technologies. My expertise extends to Python, PHP, Java, ... For more detailed information, please check out the user profile

https://www.techieclues.com/profile/techieclues

Comments (0)

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