我有datagridview,它从文件中读取一些字符串和一些日期。这是我用来存储这些数据的字典(用于添加新记录并存储日期时间值)
private Dictionary<string, DateTime> gDict = new Dictionary<string, DateTime>();
这就是我如何将数据保存到文件:
public bool SaveTableToFile()
{
System.Data.DataTable curr_table = dgv.DataSource as System.Data.DataTable;
try
{
using (System.IO.StreamWriter strwr = new System.IO.StreamWriter(filePath + @"\" + fileName, false))
{
strwr.WriteLine("__FILE_BEGIN__");
foreach (KeyValuePair<string, DateTime> kvp in gDict)
{
strwr.WriteLine("__LINE_BEGIN__");
strwr.WriteLine("Date=" + kvp.Value.ToString("dd.MM.yyyy hh:mm:ss"));
strwr.WriteLine("IP=" + kvp.Key);
strwr.WriteLine("__EOL__");
strwr.Flush();
}
strwr.WriteLine("__EOF__");
strwr.Close();
return true;
}
}
catch { return false; }
}
//刚刚注意到我终于在这里遇到了阻塞而且我的捕获很糟糕
这就是我如何从文件http://pastebin.com/uZN4CdxZ
中读取它此日期在表格中显示为时间跨度 -
DateTime now = DateTime.Now;
...
DateTime dt = new DateTime();//15.03.2013 3:01:13 //dd.MM.yyyy hh:mm:ss
dt = DateTime.ParseExact(preparedString[1], "dd.MM.yyyy hh:mm:ss", System.Globalization.CultureInfo.CurrentCulture);
TimeSpan timediff = (now - dt);
当我运行我的程序时,它会从文件中读取所有条目,计算时差并将其显示在表格中。还有问题 - 所有时差都是错误的,它还有12个小时。
当我在加载表格后添加新行时
public void TryAddNewRow(string ex_IP)
{
if (!gDict.ContainsKey(ex_IP))
{
System.Data.DataTable curr_table = dgv.DataSource as System.Data.DataTable;
System.Data.DataRow theRow = curr_table.NewRow();
DateTime dt = DateTime.Now;
theRow["Date"] = (dt - DateTime.Now);
theRow["IP"] = ex_IP;
curr_table.Rows.Add(theRow);
gDict.Add(ex_IP, dt);
}
else
{
TimeSpan ts = DateTime.Now - gDict[ex_IP];
System.Windows.Forms.MessageBox.Show("IP already exists, it was used" + Environment.NewLine + ts.Hours+" hours, "+ts.Minutes +" minutes, and "+ts.Seconds+" seconds ago.");
}
}
首先它显示零(类似于0:00:00)。但是当桌子每分钟运行一次计时器刷新时,就会变成12小时1分钟。
private void timer1_Tick(object sender, EventArgs e)
{
gTable.SaveTableToFile();
gTable.UpdateTable();
label1.Text = DateTime.Now.ToString("HH:mm.ff") + ": Table updated.";
}
public void UpdateTable()
{
CreateNewDataSource();
//reading data from file and creating rows
ReadTableFromFile();
}
private void CreateNewDataSource()
{
dgv.DataSource = null;
System.Data.DataSet myDataSet = new System.Data.DataSet();
System.Data.DataTable aTable = new System.Data.DataTable("Table 1");
myDataSet.Tables.Add("Table 1");
List<System.Data.DataColumn> columnsList = new List<System.Data.DataColumn>();
foreach (TableField curr_field in fTableFields.ftfList)
columnsList.Add(new System.Data.DataColumn(curr_field.Name, curr_field.FieldType));
foreach (System.Data.DataColumn column in columnsList)
myDataSet.Tables["Table 1"].Columns.Add(column);
dgv.DataSource = myDataSet.Tables["Table 1"];
foreach (TableField curr_field in fTableFields.ftfList)
dgv.Columns[curr_field.Name].Width = curr_field.HeaderWidth;
}
答案 0 :(得分:3)
问题源于不一致的解析格式。
在某些地方,您使用hh
(12小时格式),而在其他地方,您使用HH
(24小时格式)。
换句话说,您将时间解析为12小时格式,但您将其显示为24小时格式。
所以"1:30"
解析为13:30,并显示为"13:30"
,即使它原来可能是"01:30"
(AM)。
替换所有格式以使用HH
。
有关详细信息,请参阅Custom Date and Time Format Strings。