2017-03-09 56 views
1

语言采取将字符串转换为C#从文件到DATETIME

嗨,

我试图让员工时间计算器。我创建了3个按钮,IN,OUT和READ。在和OUT中,按下时,将系统时间保存到文件中。

Format saved in file is: OUT 3/9/2017 3:20:55 PM

我也可以读取值,但是当试图在datetime中转换它时会抛出异常。 任何人都可以指导我如何计算从文件中取得的两个值的差异。

问题是按钮3

  private void button3_Click(object sender, EventArgs e) 
    { 

     int a = 0; 
     string path = @"C:\Users\Public\WriteLines.txt"; 
     using (StreamReader sr = new StreamReader(path)) 
     { 
      string line; 
      string[] lines= new String[500]; 
      // Read and display lines from the file until the end of 
      // the file is reached. 
      while ((line = sr.ReadLine()) != null) 
      { 
       lines[a] = line; 
       a++; 
       Console.WriteLine(line); 
       Console.WriteLine(a); 
    // DateTime date3 = DateTime.Parse(lines[1]); 
     //   DateTime date4 = DateTime.Parse(lines[2]); 
     //  DateTime date4 = DateTime.ParseExact(lines[2], "d/M/yyyy h:mm:ss tt", null); 

       TimeSpan difference = DateTime.Parse(lines[1]) - DateTime.Parse(lines[2]); 
      } 
     } 
    } 
+2

解决了这个问题,我不想读所有这些垃圾。请编辑您的问题到相关的代码。 –

+1

我们不需要所有的信息和代码,我们只需要一个[最小,完整和可验证的示例](http://stackoverflow.com/help/mcve)。你需要告诉我们你得到了什么异常,并且我们需要你输入到DateTime.Parse中的字符串。您的整个帖子可能是:“为什么TimeSpan的差异= DateTime.Parse(”格式:OUT 3/9/2017 3:20:55 PM“) - DateTime.Parse(”格式:OUT 3/9/2017 3: 20:55 PM“);'抛出一个FormatException? – Quantic

回答

0

我约了太多的信息较早的意见达成一致。 话虽如此,看起来你的字符串包含“IN”或“OUT”。 DateTime.Parse()无法处理,所以解析出来,所以你只有日期时间部分的字符串提供给DateTime.Parse()。

0

对不起,我应该只写在第一位所需的代码。

即使我删除 'IN' 和 'OUT',它仍然给我的错误:

An unhandled exception of type 'System.ArgumentNullException' occurred in mscorlib.dll

Additional information: String reference not set to an instance of a String.

目前该文件中的值是

2017年3月8日7:06: 43 PM

2017年3月8日下午7点06分44秒

2017年3月8日下午7点06分44秒

2017年3月8日下午7点06分44秒

2017年3月8日下午7时06分44秒

2017年3月8日下午7时06分44秒

0

使用

TimeSpan difference = Convert.ToDateTime(lines[a]) - Convert.ToDateTime(lines[a-1]);