简体   繁体   English

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

[英]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.但是,当它们是 null 值时,它返回格式异常。 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在尝试将字符串转换为 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);

If possible, you could also change your method to accept DateTime values instead of strings如果可能,您还可以更改方法以接受 DateTime 值而不是字符串

DateTime is not nullable. DateTime不可为空。 So trying to format a string that is Null or Empty should return an exception.因此,尝试格式化 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
                 });
}

You never said what your string values were.您从未说过您的字符串值是什么。 Are they in the right format?它们的格式是否正确?

Put your try/catch routine like this:像这样放置您的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.");
  }
}

You can potentially change the DateTime to Nullable, DateTime?您可以将DateTime更改为 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.或使用string.IsNullOrEmpty()检查您传入的字符串,并添加您认为最适合处理 null 值的任何逻辑。

Use DateTime.TryParse() instead of Convert.ToDateTime().使用 DateTime.TryParse() 而不是 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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