简体   繁体   中英

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

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?

How about

Datetime dt = new DateTime(longvaluefromdatabase);

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

Read this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM