2017-03-09 19 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]);