简体   繁体   English

获取system.formatexception

[英]Getting system.formatexception

im getting an error that String was not recognized as a valid Date Time. 即时通讯收到错误消息,指出字符串未被识别为有效的日期时间。

Description: An unhandled exception occurred during the execution of the current web request. 说明:执行当前Web请求期间发生未处理的异常。 Please review the stack trace for more information about the error and where it originated in the code. 请查看堆栈跟踪,以获取有关错误及其在代码中起源的更多信息。

Exception Details: System.FormateException: String was not recognized as a valid Date Time. 异常详细信息:System.FormateException:无法将字符串识别为有效的日期时间。

Here is the place where I get the exception: 这是我得到例外的地方:

string validFrom="dd/MM/yyyy";
    {
        lstExchangeRates.Add(new KangoGiftRepository.Orm.ExchangeRate(1, cell.Value.ToString(), decimal.Parse(importSheet.Cells[startRow, 2].Value.ToString()), DateTime.ParseExact(validFrom, "dd/MM/yyyy", null)));
        startRow++; cell = importSheet.Cells[startRow, 1];
        valid = cell?.Value != null && cell.Value.ToString().Length == 3;
    }

You are getting the error because your string is not in a valid date format. 您收到错误消息,因为您的字符串格式无效。

In your code sample, validFrom should be the actual value, not the date format string. 在您的代码示例中, validFrom应该是实际值,而不是日期格式字符串。 You're getting the error because 'dd/MM/YYYY' cannot be parsed into 'dd/MM/yyyy'. 您收到错误消息是因为无法将“ dd / MM / YYYY”解析为“ dd / MM / yyyy”。 '23/10/2016' can be parsed into 'dd/MM/yyyy'. 可以将“ 23/10/2016”解析为“ dd / MM / yyyy”。

Here is a code snippet to parse dates: 这是解析日期的代码片段:

  string[] dateValues = { "30-12-2011", "12-30-2011", 
                          "30-12-11", "12-30-11" };
  string pattern = "MM-dd-yy";
  DateTime parsedDate;

  foreach (var dateValue in dateValues) {
     if (DateTime.TryParseExact(dateValue, pattern, null, 
                               DateTimeStyles.None, out parsedDate))
        Console.WriteLine("Converted '{0}' to {1:d}.", 
                          dateValue, parsedDate);
     else
        Console.WriteLine("Unable to convert '{0}' to a date and time.", 
                          dateValue);
  }

To learn more about parsing dates, visit https://msdn.microsoft.com/en-us/library/w2sa9yss(v=vs.110).aspx 要了解有关解析日期的更多信息,请访问https://msdn.microsoft.com/zh-cn/library/w2sa9yss(v=vs.110).aspx

To learn about valid format strings visit https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx 要了解有效的格式字符串,请访问https://msdn.microsoft.com/zh-cn/library/az4se3k1(v=vs.110).aspx

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

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