How DateTime Parsing Works in C#: Explanation and Examples 

If you’re just learning to program in C#, DateTime parsing can be a pain. While it’s not all that complicated when properly broken down, it can be daunting to a beginner. With a bunch of formats to remember and four different methods of doing it, an explainer is definitely in order.

The four methods, however, provide flexibility for various situations you might encounter when coding an application or working with a database. Continue reading to learn more about C#, parsing, acceptable DateTime formats, and the methods for parsing in C#. 

What is C#?

C#, pronounced ‘C sharp,’ is a high-level object-oriented programming language. If you are already familiar with C, C++, Java, or JavaScript, you’ll find C# familiar and somewhat easy to understand. Its core syntax uses the same basics found in other C-style languages, for example, semicolons denote the end of a statement. But if you’ve never learned any C family language, expect a bit of a learning curve to get up to speed. 

C# is used to build applications that run in .NET, which is a free cross-platform developer framework for building robust web, mobile, and desktop apps. You can also program IoT applications or build games from the ground up with it. 

The programming language was created by Anders Hejlsberg and Mads Torgersen when they worked for Microsoft in 2000. While C# was very popular in the early 2000s, it has slipped down the ranks as Python usage dramatically increased. Today C# has 6.5 million active developers and it is most popular for creating desktop, VR, and AR applications. 

size of programming language communities

What is parsing in C#?

In programming, parsing is part of the compiling process. Parsing involves reading text and converting it to a more useful format. A parser is a tool, a compiler, that takes a string and turns it into an abstract syntax tree so the compiler can manipulate the code.

Parsers usually have two components:

  • Lexer – also known as scanner or tokenizer, is a program that performs lexical analysis to identify ‘tokens’ that are recognizable C# language types 
  • Specific parser – multiple parsers exist, and the parser combines tokens to produce an abstract syntax tree
lexer - parser - illustration for how DateTime parsing works in C#

Accepted C# DateTime Structures

There are ten recognizable DateTime formats. These different standards allow a varying level of granularity, depending on the application’s needs. Some applications may require the full UTC string that conforms to ISO 8601, while other applications may call for only the month and year components. 

These are the recognizable components of a DateTime structure:

  • YYYY = four-digit year
  • MM   = two-digit month (01=January, etc.)
  • DD   = two-digit day of month (01 through 31)
  • hh   = two digits of hour (00 through 23) (am/pm NOT allowed)
  • mm   = two digits of minute (00 through 59)
  • ss   = two digits of second (00 through 59)
  • s    = one or more digits representing a decimal fraction of a second
  • TZD  = time zone designator (Z or +hh:mm or -hh:mm)

Dates and times can be written with different combinations of these DateTime structure components in the following acceptable formats for parsing:

DateTime Format for Strings that can be parsedExample 
String with a date and time component:   ’08/18/2018 07:22:16′ –> 8/18/2018 7:22:16 AM
String with a date component only:   ’08/18/2018′ –> 8/18/2018 12:00:00 AM
String with a month and year component only:‘8/2018’ –> 8/1/2018 12:00:00 AM
String with a month and day component only:   ‘8/18’ –> 8/18/2018 12:00:00 AM
String with a time component only:                   ’07:22:16′ –> 2/22/2018 7:22:16 AM
String with an hour and AM/PM designator only:    ‘7 PM’ –> 2/22/2018 7:00:00 PM
UTC string that conforms to ISO 8601: ‘2018-08-18T07:22:16.0000000Z’ –> 8/18/2018 12:22:16 AM
Non-UTC string that conforms to ISO 8601:            ‘2018-08-18T07:22:16.0000000-07:00’ –> 8/18/2018 7:22:16 AM
String that conforms to RFC 1123: ‘Sat, 18 Aug 2018 07:22:16 GMT’ –> 8/18/2018 12:22:16 AM
String with date, time, and time zone information:’08/18/2018 07:22:16 -5:00′ –> 8/18/2018 

C# DateTime Parsing Methods

Each of the following four DateTime parse methods is capable of parsing DateTime strings, but in slightly different ways: 

  • DateTime.Parse()
  • DateTime.ParseExact()
  • DateTime.TryParse()
  • DateTime.TryParseExact()

Let’s look at each method individually, including a few code examples. It will help you better understand the appropriate situations to use each:

1. DateTime.Parse()

The DateTime.Parse() method converts a string into a DateTime object by automatically figuring out the string’s DateTime format. The string format must match the specified format exactly. If it doesn’t match, you’ll get an exception. In this case:

catch (FormatException e)
{
    Console.WriteLine("failed to parse string");
    Console.WriteLine(e);
}

Example 1 – DateTime Array

Let’s consider the following array of dates:

string[] dates = {
    "01/02/2022 01:01:01",
    "01/02/2022",
    "1/2022",
    "1/22",
    "1 AM",
    "2022-01-02T05:20:12.0000000Z",
    "2022-01-02T05:20:12.0000000-05:00",
    "Sat, 02 Jan 2022 05:20:12 GMT",
    "2022-01-02 05:20:12 -5:00",
};

You can parse this array with the DateTime.Parse() method:

foreach (var ds in dates)
{
    var dt = DateTime.Parse(ds);
    Console.WriteLine(dt);
}

Using the dotnet run command to run the source code will output the following DateTime objects:

$ dotnet run
1/2/2022 1:01:01 AM
1/2/2022 12:00:00 AM
1/1/2022 12:00:00 AM
1/2/2022 12:00:00 AM
1/2/2022 4:00:00 AM
1/2/2022 6:20:12 AM
1/2/2022 11:20:12 AM
1/2/2022 6:20:12 AM
1/2/2022 11:20:12 AM

2. DateTime.ParseExact()

If you know the exact format that a string is using, it’s quicker and preferable to use the DateTime.ParseExact() method. You’ll need to explicitly pass in the format as a variable of the DateTime.ParseExact() method:

public static DateTime ParseExact (string s, string format, IFormatProvider? provider);

Example 1 – RFC 1123 Format

Let’s consider the following string:

var ds = "Mon Feb 14, 2022";

This string conforms to RFC 1123 format: 

‘Ddd MMM dd, yyyy’

‘Sat, 18 Aug 2018 07:22:16 GMT’ –> 8/18/2018 12:22:16 AM

It just doesn’t list the time, so the time will be assumed to be 12:00:00 AM.

To parse this string with the DateTime.Parse(Exact) method:

var dt = DateTime.ParseExact(ds, "ddd MMM dd, yyyy", CultureInfo.CurrentCulture);
Console.WriteLine(dt);

This outputs the following DateTime objects:

$ dotnet run
2/14/2022 12:00:00 AM

Example 2 – MM/DD/YYYY

Here’s another string to parse:

var ds2 = "05-10-2022";

This string is in the MM/DD/YYYY format. This means it can be parsed with the following command:  

var dt2 = DateTime.ParseExact(ds2, "MM-dd-yyyy", CultureInfo.CurrentCulture);
Console.WriteLine(dt2);

Which then outputs this DateTime object:

$ dotnet run
5/10/2022 12:00:00 AM

3. DateTime.TryParse()

The DateTime.TryParse() method tries to parse a string to a specific DateTime format. No exceptions are thrown if the format does not match the string. You can use the DateTime.TryParse() method to see if a string matches the format you expect without throwing exceptions.

Example 1 – TryParse() Fails

Here’s our string, which is clearly not in a recognizable DateTime format, but we’re going to assume we don’t know the value of this string, so we are checking it:

string ds = "not a date";

When inserted in the following if/else statement:

if (DateTime.TryParse(dateString3, out dateValue))
         Console.WriteLine("Converted '{0}' to {1}.", dateString3, dateValue);
      else
         Console.WriteLine("Unable to parse '{0}'.", dateString3);
   }

The following output is revealed:

$ dotnet run
Unable to parse ‘not a date’.

4. DateTime.TryParseExact()

The DateTime.TryParseExact() method tries to parse a string to a specific DateTime format. The format must match exactly, or an exception will be thrown, but it enhances your program and speeds it up if you have a ton of invalid DateTime strings to sort through. If the conversion succeeds, the parsed object is printed. If the method fails, an exception is thrown.

Example 1 – Conversion Fails

In this example, you’ll parse the following string:

string ds = "10/31/2022";

Using the DateTime.TryParseExact() method, including a console command to write an error message if the conversion fails:

DateTime dt;
var ok = DateTime.TryParseExact(ds, out dt);

if (ok)
{
    Console.WriteLine($"{dt:d MMMM, yyyy}");
}
else
{
    Console.WriteLine("failed to parse datetime string");
}

When you execute this source code:

$ dotnet run
failed to parse datetime string

The conversion failed because the provided format d MMMM, YYYY  does not match the string’s format of DD MM, YYYY.

Example 2 – Conversion Succeeds

In this example, the specified format matches the string:

string ds = "10/31/2022";

Using the DateTime.TryParse() method, including a console command to write an error message if the conversion fails:

DateTime dt;
var ok = DateTime.TryParse(ds, out dt);

if (ok)
{
    Console.WriteLine($"{dt: MM/dd/yyyy}");
}
else
{
    Console.WriteLine("failed to parse datetime string");
}

When you execute this source code, it successfully converts this string into the following DateTime object:

$ dotnet run
10/31/2022

The Important Basics of DateTime Parsing C#

This article has outlined all the essential concepts of DateTime parsing in C#. There are four different methods you can use to parse various DateTime string formats into DateTime objects. Each method has a different use case, which is useful to work in the different situations you’ll encounter during your programming journey. 

In case you encounter the “String was not recognized as a valid DateTime” error message while parsing text into DateTime, you can get further help from our previous article that specifically addresses this C# exception. It will explain to you in detail everything you need to know about fixing this error. It will also tell you what causes it and teach you the correct syntax. 

C# is fairly flexible, and you learned within this guide a bunch of different statements to parse your strings. Hopefully, you feel more comfortable with this topic and can’t wait to start parsing with confidence! 

Leave a Comment