c#substring错误 - StartIndex不能小于零

时间:2015-05-07 13:46:27

标签: c# substring

我有一个名为value的字符串1899-12-30 01:30:00

我想把01:30变成一个单独的字符串,我试图使用子字符串,但它一直给我一个错误,即startindex不能小于零,有人能告诉我我做错了吗?

using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT * FROM [" + sheet1 + "]", excel_con))
            {
                oda.Fill(dtExcelData);

            }
            excel_con.Close();


            if (dtExcelData.Rows.Count > 0)
            {

                foreach (DataRow rw in dtExcelData.Rows)
                {
                    //Creates StaffID
                     rw["StaffID"] = "00" + rw["Host Key of Staff"].ToString();

                    //Get duration out of DateTime
                     string Value = rw["Taught Periods Distinct as duration"].ToString();
                     string Duration = Value.Substring(Value.Length - 10, 5);

                     rw["Taught Periods Distinct as duration"] = Duration.ToString();
                }
            }

调试它说:

持续时间=" 01:30"键入字符串
价值=" 30/12/1989 01:30:00"键入字符串
Value.Length = 19输入int
rw ["讲授时间与持续时间不同"] =" 30/12/1989 01:30:00"输入对象{string}

3 个答案:

答案 0 :(得分:1)

首先添加一个断点并查看Value的值,看起来你的变量中存在无效值。

要将01:30提取到单独的字符串中,更好的方法将使用DateTime解析。因为您的字符串是有效的DateTime值。使用

DateTime parsedDateTime;
string Duration = null;
if (!DateTime.TryParseExact("1899-12-30 01:30:00", //or rw["Taught Periods Distinct as duration"].ToString();
    "yyyy-MM-dd HH:mm:ss",
    CultureInfo.InvariantCulture,
    DateTimeStyles.None,
    out parsedDateTime))
{
    Console.WriteLine("Invalid date");
}
else
{
    Duration = parsedDateTime.ToString("HH:mm", CultureInfo.InvariantCulture);
}

答案 1 :(得分:1)

实际上,您想从日期中提取时间(小时+分钟)。

为此,我建议不要进行字符串转换。相反,通过直接使用DateTime更好地使用更直接的方法,如下所示:

DateTime Value = rw["Taught Periods Distinct as duration"];
rw["Taught Periods Distinct as duration"] = Value.TimeOfDay ;

答案 2 :(得分:-4)

这有效:

string Value = "Taught Periods Distinct as duration".ToString();
string Duration = Value.Substring(Value.Length - 10, 5);

还有:

string Value2 = "1899-12-30 01:30:00";
string Duration2 = Value2.Substring(Value2.Length - 10, 5);