Convert timestamp(Datetime.ticks) from database to Datetime value before displaying it in DataGridView

半城伤御伤魂 提交于 2019-12-24 20:20:17

问题


I am using SQL server compact edition as the backend in my winform application.

I have a column timestamp in one of my tables. I have stored timestamp as follows :

DateTime dt = System.DateTime.Now;
long timestamp = dt.Ticks;

It stores a long value representing current date and time into the database.

I want to display table's data in a DataGridView control by setting its DataSource property.

When I retrieve table data using SQL query "select * from my-table" and attach to DataSource, it just displays timestamp as a long value.

My question is : How can I convert timestamp back to DateTime value in dd-mm-yyyy format before displaying it in the DataGridView?


回答1:


If you using datatable, you can do this:

resultDataTable.Columns.Add(new DataColumn("DateTime", typeof(DateTime)));
foreach (DataRow r in dt.Rows)
{
    r["DateTime"] = new DateTime(Convert.ToInt32(r["Timestamp"]);
}
dt.Columns.Remove("Timestamp");

Check this to convert sqlceresultset.resultview to datatable: Convert SQLCEResultSet resultview to datatable




回答2:


How about

Datetime dt = new DateTime(longvaluefromdatabase);

Initializes a new instance of the DateTime structure to a specified number of ticks.

Read this



来源:https://stackoverflow.com/questions/11914243/convert-timestampdatetime-ticks-from-database-to-datetime-value-before-display

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!