将 UNIX 时间转换为正常的日期和时间 C#
本文关键字:时间 日期 UNIX 转换 | 更新日期: 2023-09-27 18:30:22
我正在使用下面的代码从包含日期列的 SQLite3 数据库填充程序中的数据网格视图
此日期列以Unix时间存储,我想将其明显显示为正常日期
有没有办法在将数据网格视图中读取数据库时执行此操作?
SQLiteConnectionStringBuilder csb = new SQLiteConnectionStringBuilder();
csb.DataSource = Path.Combine(connectionPath, "sms.db");
SQLiteConnection connection = new SQLiteConnection(csb.ConnectionString);
connection.Open();
// SQL query to read the data fromt he database
SQLiteCommand command = connection.CreateCommand();
//Read Everything
string query = "SELECT * FROM message";
command.CommandText = query;
SQLiteDataAdapter dataAdaptor = new SQLiteDataAdapter(command);
DataSet dataset = new DataSet();
dataAdaptor.Fill(dataset, "Messages");
// Get the table from the data set
DataTable datatable = dataset.Tables["Messages"];
dataGridSMS.DataSource = datatable;
// This is an example of a UNIX timestamp for the date/time
double timestamp = 1116641532;
// First make a System.DateTime equivalent to the UNIX Epoch.
System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
// Add the number of seconds in UNIX timestamp to be converted.
dateTime = dateTime.AddSeconds(timestamp).ToLocalTime();
使用 DataGridView.CellFormatting Event
private void dataGridSMS_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (this.dataGridSMS.Columns[e.ColumnIndex].Name == "dateColumn")
{
if (e.Value != null)
{
try
{
// Formatting
double timestamp = Convert.ToDouble(e.Value); // if e.Value is string you must parse
System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
dateTime = dateTime.AddSeconds(timestamp).ToLocalTime();
e.Value = dateTime.ToString();
e.FormattingApplied = true;
}
catch (Exception)
{
e.FormattingApplied = false;
}
}
}
}