How to Convert String to Date Using to C#

Feb 3, 2024

2 mins read

Published in

Converting String to Date in C#: A Comprehensive Guide

Converting a string to a date is a common task in C# programming, especially when dealing with user input or data from external sources. In this blog post, we will explore different methods to achieve this conversion, along with detailed code examples.

Method 1: Using DateTime.ParseExact()

The DateTime.ParseExact() method allows you to specify the exact format of the input string that represents the date. Here’s how you can use it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
using System;

class Program
{
    static void Main()
    {
        string dateString = "2024-02-03";
        string format = "yyyy-MM-dd";
        DateTime result = DateTime.ParseExact(dateString, format, System.Globalization.CultureInfo.InvariantCulture);

        Console.WriteLine(result);
    }
}

Explanation:

  • We define a string variable dateString containing the date in the format “yyyy-MM-dd”.
  • We specify the format of the input string using the format variable.
  • We call DateTime.ParseExact() with the input string, format, and CultureInfo.InvariantCulture to indicate that no culture-specific information is needed.
  • Finally, we print the result.

Method 2: Using DateTime.TryParseExact()

The DateTime.TryParseExact() method is similar to ParseExact(), but it returns a Boolean value indicating whether the conversion succeeded, instead of throwing an exception on failure. Here’s how to use it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
using System;

class Program
{
    static void Main()
    {
        string dateString = "2024-02-03";
        string format = "yyyy-MM-dd";
        DateTime result;

        if (DateTime.TryParseExact(dateString, format, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out result))
        {
            Console.WriteLine(result);
        }
        else
        {
            Console.WriteLine("Invalid date format");
        }
    }
}

Explanation:

  • We define a string variable dateString containing the date in the format “yyyy-MM-dd”.
  • We specify the format of the input string using the format variable.
  • We call DateTime.TryParseExact() with the input string, format, CultureInfo.InvariantCulture, and DateTimeStyles.None.
  • If the conversion succeeds, we print the result; otherwise, we display an error message.

In this blog post, we have covered two methods for converting a string to a date in C#: using DateTime.ParseExact() and DateTime.TryParseExact(). Both methods provide flexibility in specifying the format of the input string and handle conversion errors gracefully. Depending on your specific requirements, you can choose the method that best suits your needs.

Sharing is caring!