C#
DateTime Parsing
String Conversion
Programming Guide
.NET

How to parse strings to DateTime in C properly?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Parsing date strings in C# is easy to get wrong because date formats depend on culture, separators, time zones, and error handling choices. The safest default is to prefer TryParseExact when you know the expected format and to use DateTimeOffset instead of DateTime when the offset matters.

Start With TryParseExact

If the input format is known, DateTime.TryParseExact is the most reliable tool because it avoids ambiguity and exceptions.

csharp
1using System;
2using System.Globalization;
3
4class Program
5{
6    static void Main()
7    {
8        var input = "2026-03-07 14:30:00";
9        var format = "yyyy-MM-dd HH:mm:ss";
10
11        bool ok = DateTime.TryParseExact(
12            input,
13            format,
14            CultureInfo.InvariantCulture,
15            DateTimeStyles.None,
16            out DateTime parsed
17        );
18
19        Console.WriteLine(ok);
20        Console.WriteLine(parsed);
21    }
22}

This approach is explicit about:

  • the expected pattern
  • the culture rules
  • the error behavior

That makes it much safer than relying on loose parsing.

Why Parse Can Surprise You

DateTime.Parse and DateTime.TryParse use culture-aware heuristics. That can be helpful for user input, but it can also produce different results on different machines.

Example:

csharp
1using System;
2using System.Globalization;
3
4class Program
5{
6    static void Main()
7    {
8        var text = "03/04/2026";
9
10        var us = DateTime.Parse(text, new CultureInfo("en-US"));
11        var gb = DateTime.Parse(text, new CultureInfo("en-GB"));
12
13        Console.WriteLine(us.ToString("yyyy-MM-dd"));
14        Console.WriteLine(gb.ToString("yyyy-MM-dd"));
15    }
16}

The same string can mean March 4 or April 3 depending on culture. That is why format-aware parsing is usually better for machine-readable data.

Parse ISO 8601 And Offsets With DateTimeOffset

If the string includes an offset or represents an instant in time, DateTimeOffset is usually the better type.

csharp
1using System;
2using System.Globalization;
3
4class Program
5{
6    static void Main()
7    {
8        var input = "2026-03-07T14:30:00+02:00";
9
10        bool ok = DateTimeOffset.TryParseExact(
11            input,
12            "O",
13            CultureInfo.InvariantCulture,
14            DateTimeStyles.None,
15            out DateTimeOffset parsed
16        );
17
18        Console.WriteLine(ok);
19        Console.WriteLine(parsed.UtcDateTime);
20    }
21}

The round-trip "O" format is ideal for serialized timestamps because it preserves precision and offset information cleanly.

Use DateTime when you mean a local or abstract calendar value. Use DateTimeOffset when you mean a real timestamp that happened at a specific instant.

Handle Multiple Known Formats

Some systems legitimately accept a small set of date formats. In that case, pass an array:

csharp
1using System;
2using System.Globalization;
3
4class Program
5{
6    static void Main()
7    {
8        string[] formats =
9        {
10            "yyyy-MM-dd",
11            "yyyy/MM/dd",
12            "dd-MM-yyyy"
13        };
14
15        var input = "2026/03/07";
16
17        bool ok = DateTime.TryParseExact(
18            input,
19            formats,
20            CultureInfo.InvariantCulture,
21            DateTimeStyles.None,
22            out DateTime parsed
23        );
24
25        Console.WriteLine(ok);
26        Console.WriteLine(parsed.ToString("yyyy-MM-dd"));
27    }
28}

This is still explicit and controlled. It is much better than allowing unlimited culture-dependent guessing.

Use DateTimeStyles Deliberately

DateTimeStyles changes how the parser interprets whitespace, offsets, and local or UTC assumptions.

For example, if you want a parsed offset time normalized to UTC:

csharp
1var ok = DateTimeOffset.TryParseExact(
2    "2026-03-07T14:30:00+02:00",
3    "O",
4    CultureInfo.InvariantCulture,
5    DateTimeStyles.AdjustToUniversal,
6    out DateTimeOffset parsed
7);

Be careful here. Parsing is not just about matching characters; it is also about deciding what the resulting time should mean inside your application.

A Good Practical Rule

For external data formats:

  • prefer TryParseExact
  • prefer CultureInfo.InvariantCulture
  • use DateTimeOffset if the offset matters

For free-form user input:

  • 'TryParse can be acceptable'
  • but use the user's culture intentionally
  • validate the result carefully before storing it

That separation keeps machine data deterministic and user-facing data flexible.

Common Pitfalls

The biggest mistake is using DateTime.Parse on machine-generated strings and assuming all environments will interpret them the same way. Culture differences make that unreliable.

Another mistake is using DateTime for timestamps that really include an offset or timezone concept. Once the offset is lost, later conversions become much harder to reason about.

People also forget to use TryParse variants and let parsing failures throw exceptions in ordinary control flow. For user input and APIs, boolean success checks are cleaner.

Finally, be explicit about format strings. A parser that "usually works" is exactly the kind that breaks in production on one unexpected input.

Summary

  • Prefer TryParseExact when the input format is known.
  • Use InvariantCulture for machine-readable dates to avoid locale surprises.
  • Use DateTimeOffset when the original string includes an offset or represents an instant in time.
  • Support multiple known formats explicitly instead of relying on loose parsing.
  • Treat parsing as both a formatting problem and a time semantics problem.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.