0

记录值。时间为“11/01/2012 11:38:01:296”

string[] capturetime = record.Time.Split(':');
string captime = capturetime[0] + ":" + 
                 capturetime[1] + ":" + 
                 capturetime[2] + "." + 
                 capturetime[3];
DateTime rightTime = Convert.ToDateTime(captime);

在第二行运行后,captime 的值为“11/01/2012 11:38:01.296” 最后一行出现错误:“索引和长度必须引用字符串中的位置。参数名称:lengthmscorlib”

我不明白为什么。因为它之前运行良好:(任何人都可以解释这一点?tks这么多

解决了,谢谢大家:)

代码 :

 string[] capturetime = newRecord.Time.Split(':');
                string captime = capturetime[0] + ":" + capturetime[1] + ":" + capturetime [2] + "." + capturetime[3];
                DateTime righttime;

                if(time[3].Length == 2)
                {
                    righttime = DateTime.ParseExact(captime, "MM/dd/yyyy hh:mm:ss.ff",
                                                     CultureInfo.InvariantCulture);
                } else
                {
                    righttime = DateTime.ParseExact(captime, "MM/dd/yyyy hh:mm:ss.fff",
                                                    CultureInfo.InvariantCulture);
                }

那么优化这些代码的任何想法????

更新 :

是我还是我的 Visual Studio 疯了???上面的新代码和旧代码一样出现异常,当我改回旧代码时。它像过去一样工作正常..wth是这样的:(

4

4 回答 4

2

You can use

string dateString =  "11/01/2012 11:38:01:296";    
DateTime date = DateTime.ParseExact(dateString , "MM/dd/yyyy hh:mm:ss:fff",
                                                CultureInfo.InvariantCulture);
于 2012-11-01T05:11:05.857 回答
0

如果你仔细看,你给的时间,没有最后一个冒号。按照正常标准,这将是一个点。正确检查 RecordTime 值。

"11/01/2012 11:38:01:296" is wrong "11/01/2012 11:38:01.296" is correct

Hence making the indices of captureTime wrong. It would be, 0, 1 and 2. 3 would be out of bounds.

于 2012-11-01T05:01:40.840 回答
0

just use DateTime.ParseExact(val, "MM/dd/yyyy HH:mm:ss:fff", new DateTimeFormatInfo()) without doing all the string splitting.

于 2012-11-01T05:19:33.683 回答
0

I believe the best way to solve this is by using the CultureInfo/DateTimeFormat strings.

However, if that's not applicable for you for some strange reason, here is a crude way of doing this.

        string val = @"11/01/2012 11:38:01:296";
        string[] parts = val.Split(' ');
        var dt = DateTime.ParseExact(parts[0], "dd/MM/yyyy", new DateTimeFormatInfo());
        double[] times = parts[1].Trim().Split(':').Select(s => double.Parse(s)).ToArray();
        dt = dt.AddHours(times[0]);
        dt = dt.AddMinutes(times[1]);
        dt = dt.AddSeconds(times[2]);
        dt = dt.AddMilliseconds(times[3]);

        // OR -- dt.AddMilliseconds(times[0] * 60 * 60 * 1000 + times[1] * 60 * 1000 + times[2] * 1000 + times[3]);
于 2012-11-01T06:43:02.987 回答