简体   繁体   中英

Validate different date formats in C#

This Question may sound silly but I tried in all the different ways I can as I want to validate different formats of date or date-time and log the error if the format is invalid.

Example: 10 March 2016, 10 Mar 16, 10 Mar 2016 

I tried using regular expression but it just checks for normal date, date-time formats say DD/MM/YYYY , YYYY/MM/DD , DD-MM-YYYY etc.

Here is my code:

bool isDate = Regex.IsMatch(Value.ToString(), @"^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$");

if (isDate == true)
{
     DateTime datetime;
     DateTime.TryParse(Value.ToString(), out datetime);
     sGetDate = datetime.ToString("dd/MM/yyyy");
     GetString.Add(sName + ":" + sGetDate);
}
else{
    //log error
}

Can anyone help me out with this? Cheers.

Is seems, you have no need in regular expressions : try parsing and see if it succeeds:

  string source = "10 Mar 16";

  ...

  // Put all allowed formats here 
  string[] formats = new string[] {
    "d MMMM yyyy",
    "d MMM yyyy",
    "d MMM yy"
  };

  if (DateTime.TryParseExact(source, 
                             formats, 
                             CultureInfo.InvariantCulture, //TODO: may be you want CultureInfo.CurrentCulture
                             DateTimeStyles.AssumeLocal, 
                             out datetime)) {
    // datetime contains valid date and time 
  }
  else {
   // log error: parsing fails
  }

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