【问题标题】:startIndex cannot be larger than length of string in c#startIndex 不能大于 C# 中字符串的长度
【发布时间】:2012-08-12 12:28:10
【问题描述】:

我试图测试员工工作的月份是否等于从他们开始工作到现在的 3 个月。这就是我想要使用的:

int totalMonth = 3;
int totalYear = 0;
int mon = DateTime.Now.Month;
int yr = DateTime.Now.Year;
//block of code that I used LinQ to Entity to get staff start work date
result = result.Where(((s => mon - int.Parse(s.StartDate.Substring(3, 2).ToString()) == totalMonth && yr -int.Parse(s.StartDate.Substring(6, 4).ToString()) == totalYear))).ToList();

我数据库中日期的格式是07/05/2012 但我得到了错误:

startIndex cannot be larger than length of string. Parameter name: startIndex

谁能告诉我,我在这里做错了什么?提前致谢。

【问题讨论】:

  • 您的代码适用于名为 result 的变量。但是我们既看不到类型也看不到它的当前值。你能详细说明一下吗?

标签: c#


【解决方案1】:

我数据库中日期的格式是 07/05/2012

很可能日期以二进制形式存储并且没有格式。您在列出记录时看到的可能与在 C# 中发生的不同。

使用调试器找出result.First().StartDate 的实际外观。可能是"5-7-12"

【讨论】:

  • 但是数据类型是varchar(50)而不是date
  • 你允许 NULL 日期吗?因为至少有一条记录少于 6 个字符。
  • @socheata 这是你的根本问题。您应该将日期存储为日期,而不是字符串。
猜你喜欢
  • 2013-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-02
相关资源
最近更新 更多