简体   繁体   中英

Format Exception: String not recognized as a valid datetime

My code works fine as far as I give the values for Begin date and enddate. However, when they are null values, it returns the format exception. This is what I did:

public static string CheckInsertRecord(String EventType, String BeginDate, String EndDate) 
{
    NCDCPoint ncdc = new NCDCPoint();
    CEOSurveyDataContext CDC = new CEOSurveyDataContext();
    int et = Convert.ToInt32(EventType);
    CultureInfo provider = CultureInfo.InvariantCulture;
    DateTime b = Convert.ToDateTime(BeginDate);
    DateTime e = Convert.ToDateTime(EndDate);

    var query = (from n in CDC.NCDCPoints
                where n.EVENT_TYPE_ID == et && n.BeginDate == b && n.EndDate == e
                select new { 
                   n.EVENT_TYPE_ID,
                   BeginDate =  n.BeginDate.ToString("yyyy-MM-dd",provider),
                   EndDate = n.EndDate.ToString(),
                   n.BeginLATLONG,
                   n.EndLATLONG
                });
   if (query.Any())
   {
       return new JavaScriptSerializer().Serialize(query.ToList());
   }
   else
   {
       return "No duplicate";
   }
}

Putting try and catch was not useful as I cannot access the return values. Can u please let me know how to deal with this error.

You could check to see if the strings are null before trying to convert them to DateTimes

if (BeginDate == null || EndDate == null) {
    // handle it appropriately, perhaps by setting a default or returning
}

DateTime b = Convert.ToDateTime(BeginDate);
DateTime e = Convert.ToDateTime(EndDate);

If possible, you could also change your method to accept DateTime values instead of strings

DateTime is not nullable. So trying to format a string that is Null or Empty should return an exception.

public static string CheckInsertRecord(String eventType, String beginDate, String endDate)
{
    NCDCPoint ncdc = new NCDCPoint();
    CEOSurveyDataContext CDC = new CEOSurveyDataContext();
    int et = Convert.ToInt32(eventType);
    CultureInfo provider = CultureInfo.InvariantCulture;

    String queryBeingDate = string.Empty;
    String queryEndDate = string.Empty;
    DateTime beginDateTime;
    DateTime endDateTime;
    if (DateTime.TryParse(beginDate, out beginDateTime))
    {
       queryBeingDate = beginDateTime.ToString("yyyy-MM-dd");
    }

    if(DateTime.TryParse(endDate, out endDateTime))
    {
       queryEndDate = endDate;
    }

    var query = (from n in CDC.NCDCPoints
                 where n.EVENT_TYPE_ID == et && n.BeginDate == b && n.EndDate == e
                 select new
                 {
                     n.EVENT_TYPE_ID,
                     BeginDate = queryBeingDate,
                     EndDate = queryEndDate,
                     n.BeginLATLONG,
                     n.EndLATLONG
                 });
}

You never said what your string values were. Are they in the right format?

Put your try/catch routine like this:

void test(string BeginDate, string EndDate) {
  DateTime noDate = new DateTime(1900, 1, 1);
  DateTime b;
  DateTime e;
  try {
    b = Convert.ToDateTime(BeginDate);
  } catch (Exception error) {
    b = noDate;
    MessageBox.Show("Invalid Format: " + BeginDate);
  }
  try {
    e = Convert.ToDateTime(EndDate);
  } catch (Exception error) {
    e = noDate;
    MessageBox.Show("Invalid Format: " + EndDate);
  }
  if (e < b) {
    throw new Exception("End Date can not be before Begin Date.");
  }
}

You can potentially change the DateTime to Nullable, DateTime? or check the strings you're passing in with string.IsNullOrEmpty() and add whatever logic you think's best to handle null values.

Use DateTime.TryParse() instead of Convert.ToDateTime(). That never throws an exception and returns a bool to tell you if the conversion worked.

substitute

 DateTime b = Convert.ToDateTime(BeginDate);
    DateTime e = Convert.ToDateTime(EndDate);

with

 DateTime b, e;
  if(!DateTime.TryParse(BeginDate,out b))
      b = YOurDefaultBeginDate;
  if(!DateTime.TryParse(EndDate,out e))
      e = YOurDefaultEndDate;

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