Parsing a DateTime from a string in C#

By FoxLearn 3/14/2025 2:56:59 AM   155
In C#, you can convert a string to a DateTime using the following methods:
  • DateTime.Parse() (or TryParse()): This is useful for parsing a variety of standard formats, including both culture-specific formats and the ISO-8601 format.
  • DateTime.ParseExact() (or TryParseExact()): This is used to parse a string that matches a specific DateTime format exactly.

Below, I'll demonstrate how both methods work with various DateTime formats.

Using DateTime.Parse()

The DateTime.Parse() method can handle a broad range of standard DateTime formats, both culture-specific and ISO-8601 formats (the default format used for JSON serialization). By default, it uses the current culture for parsing. If only partial information is provided (like just a date), it makes assumptions to fill in the missing details.

Here are a few examples using DateTime.Parse() to handle various standard DateTime formats:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Culture-specific formats (en-US culture: M/d/yyyy h:mm:ss AM|PM)
 
var dateAndTime = DateTime.Parse("14/03/2025 8:15:10 AM");
Console.WriteLine(dateAndTime);
// Outputs: 14/03/2025 8:15:10 AM
 
var longDate = DateTime.Parse("Friday, March 14, 2025");
Console.WriteLine(longDate);
// Outputs: 14/03/2025 12:00:00 AM (assumes midnight)
 
var dateOnly = DateTime.Parse("14/03/2025");
Console.WriteLine(dateOnly);
// Outputs: 14/03/2025 12:00:00 AM (assumes midnight)
 
var timeOnly = DateTime.Parse("08:15:10");
Console.WriteLine(timeOnly);
// Outputs: 14/03/2025 8:15:10 AM (assumes today's date)
 
// ISO-8601 formats
 
var iso8601WithTimeZone = DateTime.Parse("2025-03-14T08:15:10.4068309-04:00");
Console.WriteLine(iso8601WithTimeZone);
// Outputs: 14/03/2025 8:15:10 AM
 
var iso8601UTC = DateTime.Parse("2025-03-14T12:15:10.4068309Z");
Console.WriteLine(iso8601UTC);
// Outputs: 14/03/2025 8:15:10 AM

If DateTime.Parse() is unable to figure out the format automatically, it throws a FormatException.

To avoid this, you can use DateTime.TryParse() for better error handling:

1
2
3
4
5
6
7
8
if (DateTime.TryParse("050323", out DateTime result))
{
    // Use the result
}
else
{
    // Failed to parse
}

Using DateTime.ParseExact()

The DateTime.ParseExact() method is used when you want to parse a string that matches a specific format exactly.

This method is ideal in two cases:

  1. When you need to parse a custom (non-standard) DateTime format.
  2. When you only want to accept a specific DateTime format, whether standard or custom.

Here are some examples using DateTime.ParseExact() with different format strings:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Custom formats
 
var dateMMddyy = DateTime.ParseExact("140325", "MMddyy", CultureInfo.InvariantCulture);
Console.WriteLine(dateMMddyy);
// Outputs: 14/03/2025 12:00:00 AM (assumes midnight)
 
var dateyyyyMMdd = DateTime.ParseExact("20250314", "yyyyMMdd", CultureInfo.InvariantCulture);
Console.WriteLine(dateyyyyMMdd);
// Outputs: 14/03/2025 12:00:00 AM (assumes midnight)
 
var dateFormatted = DateTime.ParseExact("2025-03-14", "yyyy-dd-MM", CultureInfo.InvariantCulture);
Console.WriteLine(dateFormatted);
// Outputs: 14/03/2025 12:00:00 AM (assumes midnight)
 
// ISO-8601 formats
 
var iso8601WithTimeZone = "2025-03-14T08:15:10.4068309-04:00";
var dateISO8601 = DateTime.ParseExact(iso8601WithTimeZone, "O", CultureInfo.InvariantCulture);
Console.WriteLine(dateISO8601);
// Outputs: 14/03/2025 8:15:10 AM
 
var iso8601UTC = "2025-03-14T12:15:10.4068309Z";
var dateUTC = DateTime.ParseExact(iso8601UTC, "O", CultureInfo.InvariantCulture);
Console.WriteLine(dateUTC);
// Outputs: 14/03/2025 8:15:10 AM

Note that the ParseExact() method uses DateTimeStyles.None by default, so you don't need to specify it unless you need custom handling.

If DateTime.ParseExact() cannot parse the date according to the specified format, it will throw a FormatException.

For better error handling, use DateTime.TryParseExact():

1
2
3
4
5
6
7
8
9
if (DateTime.TryParseExact(dateString, "MMddyy",
    CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime result))
{
    // Use result
}
else
{
    // Parsing failed
}

Common DateTime Format Specifiers

When using DateTime.ParseExact(), the format string you provide can include format specifier characters, such as MM or yyyy, to specify how the date and time should be parsed.

Format SpecifierDescriptionExample
dd/MM/yyyyDay (2 digits), Month (2 digits), Year (4 digits)03/05/2025
M/d/yyyyMonth (1-2 digits), Day (1-2 digits), Year (4 digits)5/3/2025
yyyy-MM-ddYear (4 digits), Month (2 digits), Day (2 digits)2025-05-03
yyyyMMddYear (4 digits), Month (2 digits), Day (2 digits)20250503
HH:mm24-hour time format14:15 (2:15 PM)
oISO-8601 format2025-05-03T12:15:10.4068309Z

Parsing Two-Digit Years

Using two-digit years can be problematic because you lose clarity on the exact year. When parsing a two-digit year with DateTime.ParseExact(), the system will use the TwoDigitYearMax property to determine how it should interpret the year. By default, TwoDigitYearMax is set to 2049.

For example, if you need to parse a two-digit year "9912", it may be interpreted as 1999. If you want it to be interpreted as 2099, you can set TwoDigitYearMax to 2100:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
string date = "2503"// Example of a two-digit year
 
CultureInfo culture = new CultureInfo("en-US");
culture.Calendar.TwoDigitYearMax = 2100;
 
if (DateTime.TryParseExact(date, "yyMM", culture, DateTimeStyles.None, out DateTime dt))
{
    Console.WriteLine($"Parsed {date} into {dt}");
}
else
{
    Console.WriteLine($"Unable to parse {date}");
}
// Outputs: Parsed 2503 into 03/14/2025 12:00:00 AM

If you want to assume the two-digit year is within the next 99 years, you can set TwoDigitYearMax to the current year plus 99:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
string date = "2512"// Example two-digit year scenario
 
CultureInfo culture = new CultureInfo("en-US");
culture.Calendar.TwoDigitYearMax = DateTime.Now.Year + 99;
 
if (DateTime.TryParseExact(date, "yyMM", culture, DateTimeStyles.None, out DateTime dt))
{
    Console.WriteLine($"Parsed {date} into {dt}");
}
else
{
    Console.WriteLine($"Unable to parse {date}");
}
// Outputs: Parsed 2512 into 12/14/2025 12:00:00 AM

Handling Uncertainty with Two-Digit Years

Two-digit years can be particularly problematic when parsing birthdates or expiration dates, where you can’t be certain whether the year refers to the past or the future.

For instance, if you have the birthdate "1/1/19", it could be "1/1/1999" or "1/1/1919". If you're uncertain, the best approach is to have a person double-check the results to confirm the correct year. This is one of the challenges with using two-digit years: there's always a chance that the system makes the wrong guess.