格式异常:字符串未被识别为有效的日期时间

本文关键字:有效 日期 时间 识别 异常 字符串 格式 | 更新日期: 2023-09-27 18:00:33

只要我给出Begin date和enddate的值,我的代码就可以正常工作。但是,当它们为空值时,它会返回格式异常。这就是我所做的:

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";
   }
}

放入try-and-catch没有用,因为我无法访问返回值。你能告诉我如何处理这个错误吗。

格式异常:字符串未被识别为有效的日期时间

DateTime不可为null。因此,尝试格式化Null或Empty的字符串应该会返回异常。

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
                 });
}

在尝试将字符串转换为DateTimes 之前,可以检查字符串是否为null

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);

如果可能的话,您还可以更改方法以接受DateTime值,而不是字符串

您从未说过您的字符串值是什么。它们的格式正确吗?

将您的try/catch例程设置为:

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.");
  }
}

您可以将DateTime更改为Nullable、DateTime?,或者检查您使用string.IsNullOrEmpty()传递的字符串,并添加您认为最适合处理null值的任何逻辑。

使用DateTime.TryParse()而不是Convert.ToDateTime()。这不会引发异常,并返回一个bool来告诉您转换是否有效。

替代

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

带有

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