Check if a string is in a specific date format

Hi I'm receiving a string with a date format yyyy-MM-dd , but I want to compare it with a format dd-MM-yyyy in case it is not the same, sure is not, I want to convert it, the problem for me it's not to convert, it's to compare both formats... so I imagine maybe it's something like this

var dt = obj.date; //this a string

if (dt.formatDateorsomethingIguess == "dd/MM/yyyy") //this is the part I'm asking for
{
     usedt(dt);
} 
else 
{
    DateTime dt_format = DateTime.ParseExact(dt.Trim(), "dd-MM-yyyy",
    System.Globalization.CultureInfo.InvariantCulture);
    usedt(dt_format);
}

Upvotes: 2

Views: 5958

Answers (3)

bytedev
bytedev

Reputation: 9119

public static class StringExtensions
{
    public static bool IsDateTime(this string source, string format)
    {
        return DateTime.TryParseExact(source, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out _);
    }
}

Just call this method twice with your two different formats.

Upvotes: 2

user10013140
user10013140

Reputation:

have you tried to see something like a Regular expression?

i found this one > (([1-2][0-9])|([1-9])|(3[0-1]))/((1[0-2])|([1-9]))/[0-9]{4}

matches with 21/03/1995

Upvotes: 0

John Wu
John Wu

Reputation: 52280

You can solve this with a couple calls to TryParseExact:

public static DateTime ParseDate(string input)
{
    DateTime result;

    if (DateTime.TryParseExact(input, "yyyy-MM-dd", CultureInfo.CurrentCulture, DateTimeStyles.None, out result)) return result;
    if (DateTime.TryParseExact(input, "dd-MM-yyyy", CultureInfo.CurrentCulture, DateTimeStyles.None, out result)) return result;

    throw new FormatException();
}

Give it a quick test:

public static void Main()
{
    string[] tests = new string[] { "2018-06-29", "29-06-2018","Invalid" };

    foreach (var t in tests)
    {
        var result = ParseDate(t);
        Console.WriteLine( "Year: {0}  Month: {1}  Day: {2}", result.Year, result.Month, result.Day );
    }
}

Output:

Year: 2018  Month: 6  Day: 29
Year: 2018  Month: 6  Day: 29
Run-time exception (line 18): One of the identified items was in an invalid format.

Sample code on DotNetFiddle

Upvotes: 4

Related Questions