demo
demo

Reputation: 6235

Compare DateTime and date as string

I have value of DateTime and date as string. String date can be in unknown format (1 of 2 in my case : "MMM dd yyyy" or "dd MMM" ). I need to check if dates are eaqual.

Is there any other solution than trying to parse string date with first and second formats and if one return DateTime than compare with DateTime Type?

Upvotes: 0

Views: 461

Answers (1)

Farhad Jabiyev
Farhad Jabiyev

Reputation: 26635

Of course. You can use DateTime.ParseExact method. There are several overloads of the function.

One of the overloads is ParseExact(String, String[], IFormatProvider, DateTimeStyles).

Converts the specified string representation of a date and time to its DateTime equivalent using the specified array of formats, culture-specific format information, and style. The format of the string representation must match at least one of the specified formats exactly or an exception is thrown.

string[] formats= {"MMM dd yyyy", "dd MMM"};

var dateValue = DateTime.ParseExact(dateString,
                   formats, 
                   CultureInfo.InvariantCulture,
                   DateTimeStyles.None);

Keep in mind that, the format of the string representation must match at least one of the specified formats exactly or an exception is thrown. If you didn't want to use try/catch block explicitly, then your best choice will be TryParseExact method. This will return true if the parameter was converted successfully; otherwise, false.

DateTime dateValue;

Nullable<DateTime> result = DateTime.TryParseExact(dateString, formats, 
          CultureInfo.InvariantCulture,
          DateTimeStyles.None, 
          out dateValue)) ? 
    dateValue :
    (DateTime?)null;

Upvotes: 5

Related Questions