简体   繁体   中英

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?

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM