【问题标题】:Convert UNIX time to normal Date & Time C#将 UNIX 时间转换为正常的日期和时间 C#
【发布时间】:2012-04-08 16:31:57
【问题描述】:

我正在我的程序中从 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;

【问题讨论】:

标签: c# visual-studio-2010 datagridview unix-timestamp


【解决方案1】:
// 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();

【讨论】:

    【解决方案2】:

    使用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;
                    }
                }
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-22
      • 2015-01-07
      • 1970-01-01
      • 1970-01-01
      • 2018-07-30
      • 2019-04-24
      • 1970-01-01
      • 2011-08-23
      相关资源
      最近更新 更多