Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

C# Dictionary

  1. Home
  2. C# Dictionary
  3. DateTime.Parse() / DateTime.TryParse()

DateTime.Parse() / DateTime.TryParse()

Since: C# 1.0(2002)

Converts a string representing a date/time to a DateTime value using DateTime.Parse(), or use the safer DateTime.TryParse() which does not throw an exception on failure.

Syntax

DateTime dt = DateTime.Parse(string s);

// Attempts conversion and returns true on success or false on failure (no exception).
bool success = DateTime.TryParse(string s, out DateTime result);

// Converts using a specified format.
DateTime dt = DateTime.ParseExact(string s, string format, IFormatProvider provider);
bool success = DateTime.TryParseExact(string s, string format, IFormatProvider provider, DateTimeStyles style, out DateTime result);

Method List

MethodDescription
DateTime.Parse(s)Converts a string to DateTime. Throws a FormatException if the conversion fails.
DateTime.TryParse(s, out result)Returns true and stores the converted value in result on success. Returns false on failure without throwing an exception.
DateTime.ParseExact(s, format, provider)Converts only when the string exactly matches the specified format.
DateTime.TryParseExact(s, format, provider, style, out result)The exception-free version of ParseExact.

Sample Code

Program.cs
using System;
using System.Globalization;

// Convert using DateTime.Parse().
DateTime dt1 = DateTime.Parse("2024/01/15");
Console.WriteLine(dt1); // 1/15/2024 12:00:00 AM

DateTime dt2 = DateTime.Parse("2024-03-20 14:30:00");
Console.WriteLine(dt2); // 3/20/2024 2:30:00 PM

// Convert safely using TryParse() (recommended for user input).
string input = "2024/06/01";
if (DateTime.TryParse(input, out DateTime result))
{
    Console.WriteLine($"Converted: {result:yyyy/M/d}");
}
else
{
    Console.WriteLine("Conversion failed.");
}

// A string that cannot be converted returns false.
bool ok = DateTime.TryParse("abc", out DateTime failResult);
Console.WriteLine($"Success: {ok}"); // False

// Specify a strict format using ParseExact().
DateTime dt3 = DateTime.ParseExact("20240115", "yyyyMMdd", CultureInfo.InvariantCulture);
Console.WriteLine(dt3); // 1/15/2024 12:00:00 AM

// Example using TryParseExact().
bool parseOk = DateTime.TryParseExact(
    "15-01-2024",
    "dd-MM-yyyy",
    CultureInfo.InvariantCulture,
    DateTimeStyles.None,
    out DateTime dt4
);
Console.WriteLine($"Success: {parseOk}, Result: {dt4:yyyy/MM/dd}");

Run the following command:

dotnet script datetime_parse_tryparse.csx
1/15/2024 12:00:00 AM
3/20/2024 2:30:00 PM
Converted: 2024/6/1
Success: False
1/15/2024 12:00:00 AM
Success: True, Result: 2024/01/15

Practical Pattern: Safe Parsing of Form Input

User-entered date strings can have unpredictable formats, so use TryParse with error handling. This example tries multiple formats.

FormInputParse.cs
using System;
using System.Globalization;

// Parses a user-entered date string.
static bool TryParseDate(string input, out DateTime date)
{
    // Tries multiple formats.
    string[] formats = { "yyyy/MM/dd", "yyyy-MM-dd", "yyyyMMdd", "MM/dd/yyyy" };
    return DateTime.TryParseExact(
        input,
        formats,
        CultureInfo.InvariantCulture,
        DateTimeStyles.None,
        out date
    );
}

// Test: activity log dates for Rintaro Okabe
string[] inputs = { "2024/01/15", "2024-03-20", "20240601", "invalid" };
foreach (string s in inputs)
{
    if (TryParseDate(s, out DateTime parsed))
        Console.WriteLine($"[OK] {s} → {parsed:yyyy/M/d}");
    else
        Console.WriteLine($"[NG] {s} → Conversion failed");
}

Run the following command:

dotnet script form_input_parse.csx
[OK] 2024/01/15 → 2024/1/15
[OK] 2024-03-20 → 2024/3/20
[OK] 20240601 → 2024/6/1
[NG] invalid → Conversion failed

Practical Pattern: Parsing Dates from Filenames

When extracting dates from log filenames or similar sources with a fixed format, ParseExact is the right tool.

FileNameParse.cs
using System;
using System.Globalization;

// Extracts dates from log filenames (e.g., log_20240115.txt).
string[] fileNames = { "log_20240115.txt", "log_20240316.txt", "log_20241231.txt" };

foreach (string fileName in fileNames)
{
    // Extracts the 8-digit date portion from the filename.
    string datePart = fileName.Replace("log_", "").Replace(".txt", "");
    DateTime fileDate = DateTime.ParseExact(datePart, "yyyyMMdd", CultureInfo.InvariantCulture);

    // Determines whether the file is 30 or more days old.
    TimeSpan diff = DateTime.Today - fileDate;
    bool isOld = diff.TotalDays >= 30;
    Console.WriteLine($"{fileName}: {fileDate:yyyy/MM/dd} → {(isOld ? "Delete" : "Keep")}");
}

Run the following command:

dotnet script filename_parse.csx
log_20240115.txt: 2024/01/15 → Delete
log_20240316.txt: 2024/03/16 → Delete
log_20241231.txt: 2024/12/31 → Keep

Common Mistakes

Common Mistake 1: Parse() Throws an Exception

DateTime.Parse() throws a FormatException when parsing fails. Use TryParse for user input and external data.

using System;

// NG: Using Parse() on user input can throw an exception.
string userInput = "January 15, 2024 (unknown format)";
DateTime dt = DateTime.Parse(userInput); // FormatException is thrown.

Run the following command:

dotnet run
Unhandled exception. System.FormatException: String 'January 15, 2024 (unknown format)' was not recognized as a valid DateTime.

The following example demonstrates this:

using System;

// OK: TryParse() handles failure without throwing an exception.
string userInput = "January 15, 2024 (unknown format)";
if (DateTime.TryParse(userInput, out DateTime dt))
    Console.WriteLine($"Converted: {dt}");
else
    Console.WriteLine("Conversion failed. Please check the input format.");

Run the following command:

dotnet run
Conversion failed. Please check the input format.

Common Mistake 2: Omitting CultureInfo

ParseExact uses the current culture when CultureInfo is omitted. Formats containing English month names such as "Jan" may fail to parse in non-English environments unless CultureInfo.InvariantCulture is specified.

using System;
using System.Globalization;

// NG: "Jan" may not be recognized as a month name in non-English environments.
// DateTime.ParseExact("15-Jan-2024", "dd-MMM-yyyy", null);

// OK: Specify CultureInfo.InvariantCulture to ensure locale-independent parsing.
DateTime dt = DateTime.ParseExact(
    "15-Jan-2024",
    "dd-MMM-yyyy",
    CultureInfo.InvariantCulture
);
Console.WriteLine(dt); // 1/15/2024 12:00:00 AM

Run the following command:

dotnet run
1/15/2024 12:00:00 AM

Overview

When converting strings from user input or files to DateTime, use TryParse() or TryParseExact(), which do not throw exceptions. Use Parse() only for strings with a guaranteed format, such as constants or database values.

When the format is fixed to a specific pattern (such as filenames in yyyyMMdd format), ParseExact() is convenient. Specifying CultureInfo.InvariantCulture ensures locale-independent conversion.

For formatting a DateTime value after conversion, see DateTime.ToString() / DateTime.AddDays().

If you find any errors or copyright issues, please .