DateTime.ParseExactStringStringIFormatProvider

suggest change

Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.

Convert a specific format string to equivalent DateTime

The string 08-07-2016 11:30:12 PM uses the pattern MM-dd-yyyy hh:mm:ss tt. tt must match the culture's AM/PM designator, so an English PM parses reliably with CultureInfo.InvariantCulture.

string str = "08-07-2016 11:30:12 PM";
DateTime date = DateTime.ParseExact(str, "MM-dd-yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);

Convert a date time string to equivalent DateTime object without any specific culture format

A string in the dd-MM-yy hh:mm:ss tt pattern can be parsed without using the current culture:

string str = "17-06-16 11:30:12 PM";
DateTime date = DateTime.ParseExact(str, "dd-MM-yy hh:mm:ss tt", CultureInfo.InvariantCulture);

Parse one of several patterns

The same call can accept either 23-12-2016 or 12/23/2016:

string input = "23-12-2016"; // or "12/23/2016"
string[] formats = { "dd-MM-yyyy", "MM/dd/yyyy" };
DateTime parsed = DateTime.ParseExact(input, formats, CultureInfo.InvariantCulture, DateTimeStyles.None);

Add using System.Globalization; for CultureInfo.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents