Daphne
Daphne

Reputation: 21

Extract the DateTime format from a given date string

I was wondering if there was a way to extract the DateTime format from a given date string. In C# For example:

var dateString = "12/10/2018";
var format = GetDateFormat(dateString);

and then the format will be like 'long date time' or something.

Upvotes: 2

Views: 1838

Answers (3)

John Wu
John Wu

Reputation: 52240

There's no built-in function or anything, but you could write one yourself. Here is a short example that checks for three possible formats; you can add as many more as you like just by adding to the list.

If you need to support unusual formats (e.g. formats that can't be auto-detected by DateTime.Parse() then you may need a slightly different solution that tests the input using DateTime.ParseExact(), like BACON's answer.

public class Program
{
    //Returns a string indicating the format of the input, or null if could not be detected
    public static string GetDateTimeFormatCode(string dateTimeString)
    {
        //Parse the input
        DateTime dateTime;
        if (!DateTime.TryParse(dateTimeString, out dateTime)) return null;

        return
        (
            new string[]
            {
                "M/d/yyyy",
                "d MMM yyyy",
                "d MMMM yyyy",
                "dddd MMMM d yyyy"
            }
        )
        .Where( c => dateTime.ToString(c) == dateTimeString )
        .FirstOrDefault();
    }

    public static void Main()
    {
        var tests = new List<string>
        {
            @"21 May 2018",
            @"6/21/2018",
            @"Monday May 21 2018"
        };

        foreach (var t in tests)
        {
            Console.WriteLine("Input '{0}' uses format '{1}'", t, GetDateTimeFormatCode(t) ?? "?");
        }

    }
}

Output:

Input '21 May 2018' uses format 'd MMM yyyy'
Input '6/21/2018' uses format 'M/d/yyyy'
Input 'Monday May 21 2018' uses format 'dddd MMMM d yyyy'

Code on DotNetFiddle

Upvotes: 0

Lance U. Matthews
Lance U. Matthews

Reputation: 16606

Via hard-coding or reflection (shown below) you could retrieve the value of all properties of the DateTimeFormatInfo class whose name end with "Pattern", then attempt parsing using those patterns and see which ones are successful. You're then limited to the patterns provided by that class and whichever culture(s) you choose to use, though.

DateTimeFormatInfo formatInfo = DateTimeFormatInfo.CurrentInfo;
IEnumerable<PropertyInfo> patternProperties = formatInfo.GetType().GetProperties()
    .Where(property => property.Name.EndsWith("Pattern"));

foreach (PropertyInfo patternProperty in patternProperties)
{
    string pattern = (string) patternProperty.GetValue(formatInfo);
    bool wasParsed = DateTime.TryParseExact(dateString, pattern, formatInfo, DateTimeStyles.None, out DateTime _);

    Console.WriteLine($"{patternProperty.Name} (\"{pattern}\"): {wasParsed}");
}

On my system (en-US) the above code produces the following output:

FullDateTimePattern ("dddd, MMMM d, yyyy h:mm:ss tt"): False
LongDatePattern ("dddd, MMMM d, yyyy"): False
LongTimePattern ("h:mm:ss tt"): False
MonthDayPattern ("MMMM d"): False
RFC1123Pattern ("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'"): False
ShortDatePattern ("M/d/yyyy"): True
ShortTimePattern ("h:mm tt"): False
SortableDateTimePattern ("yyyy'-'MM'-'dd'T'HH':'mm':'ss"): False
UniversalSortableDateTimePattern ("yyyy'-'MM'-'dd HH':'mm':'ss'Z'"): False
YearMonthPattern ("MMMM yyyy"): False

Upvotes: 1

Sergey Slepov
Sergey Slepov

Reputation: 2111

You could try DateTime.TryParseExact with a set of predefined formats. Those that match will be the format(s) you are looking for.

Upvotes: 0

Related Questions