Convert a String to a DateTime in C#

Convert a String to a DateTime in C#

In this article, how to Convert a String to a DateTime in C#

DateTime.TryParseExact Method

using System;
using System.Globalization;
 
public class usingcsharp
{
    public static void Main()
    {
        string date = "11/20/2020";
 
        DateTime dateTime;
        string[] validformats = new[] { "MM/dd/yyyy", "yyyy/MM/dd", "MM/dd/yyyy HH:mm:ss", 
                                        "MM/dd/yyyy hh:mm tt", "yyyy-MM-dd HH:mm:ss,fff" };
 
        CultureInfo provider = CultureInfo.InvariantCulture;
 
        if (DateTime.TryParseExact(date, validformats, provider,
                                    DateTimeStyles.None, out dateTime))
        {
            Console.WriteLine("The specified date is valid: " + dateTime);
        }
        else
        {
            Console.WriteLine("Unable to parse the specified date");
        }
    }
}
 
/*
    Output: The specified date is valid: 20-11-2020 12.00.00 AM
*/

 

DateTime.ParseExact Method

using System;
using System.Globalization;
 
public class usingcsharp
{
    public static void Main()
    {
        string date = "11/20/2020";
 
 
        string[] validformats = new[] { "MM/dd/yyyy", "yyyy/MM/dd", "MM/dd/yyyy HH:mm:ss", 
                                        "MM/dd/yyyy hh:mm tt", "yyyy-MM-dd HH:mm:ss,fff" };
 
        CultureInfo provider = new CultureInfo("en-US");
        
        try {
            DateTime dateTime = DateTime.ParseExact(date, validformats, provider);
            Console.WriteLine("The specified date is valid: " + dateTime);
        }
        catch (FormatException)
        {
            Console.WriteLine("Unable to parse the specified date");
        }
    }
}
 
/*
    Output: The specified date is valid: 20-11-2020 12.00.00 AM
*/

 

DateTime.TryParse Method

using System;
 
public class Example
{
    public static void Main()
    {
        string date = "20/11/2020";
 
        DateTime dateTime;
        if (DateTime.TryParse(date, out dateTime))
        {
            Console.WriteLine("The specified date is valid: " + dateTime);
        }
        else
        {
            Console.WriteLine("Unable to parse the specified date");
        }
    }
}
 
/*
    Output: The specified date is valid: 20-11-2020 12.00.00 AM
*/

 

DateTime.Parse Method

sing System;
 
public class usingcsharp
{
    public static void Main()
    {
        string date = "20/11/2020";
 
        try
        {
            DateTime dateTime = DateTime.Parse(date);
            Console.WriteLine("The specified date is valid: " + dateTime);
        }
        catch (FormatException)
        {
            Console.WriteLine("Unable to parse the specified date");
        }
    }
}
 
/*
    Output: The specified date is valid: 20-11-2020 12.00.00 AM
*/

2021-10-03