Click here to Skip to main content
15,748,330 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Stored in a SQL table is a date/time field and it is defined as:

CreationDateTime datetime2(7) allow nulls and has stored in it 2023-06-06 09:28:37.6271104.

I have never processed a datetime beyond the standard MM/dd/yyyy hh:mm:ss. When I read the field from the databse table:

creationDateTime = Reader["CreationDateTime"].ToString();

all I get is 2023-06-06 09:28:37 and not the 2023-06-06 09:28:37.6271104.

What I have tried:

I have tried everything but nothing works. What am I doing wrong? Thanks in advance for the help?
Updated 6-Jun-23 10:22am
PIEBALDconsult 6-Jun-23 19:29pm    
Dunno. I think something is truncating it along the way. Could be the query or something.
Richard Deeming 7-Jun-23 4:46am    
Try reading the value as a DateTime, not a string:
int index = Reader.GetOrdinal("CreationDateTime");
DateTime? creationDateTime = Reader.IsDBNull(index) ? null : Reader.GetDateTime(index);

If you still get a truncated value, then you need to check the query to see what's truncating it.
Member 13694735 7-Jun-23 14:36pm    
this did the trick
var d = (DateTime)Reader["CreationDateTime"];
var dd = d.ToString("MM/dd/yyyy hh:mm:ss.fffffff tt");

1 solution

You are using the default ToString because you don't provide any specific formatting info.
Provide the right format, and you should get what you want: Formatting a DateTime for display - format string description[^]
Share this answer
Member 13694735 6-Jun-23 16:37pm    
I do this using "yyyy-MM-dd hh:mm:ss.fffffff" and this what I get 2023-06-06 09:28:37.0000000.
OriginalGriff 7-Jun-23 0:40am    
Without your actual code fragment, we can't help much further: certainly the data returned is fine for me:
            string strConnect = SMDBSupport.SMInstanceStorage.GetInstanceConnectionString("Testing");
            using (SqlConnection con = new SqlConnection(strConnect))
                    using (SqlDataAdapter da = new SqlDataAdapter("Select * from Table_3", con))
                        using (DataTable dt = new DataTable())
                            myDataGridView.DataSource = dt;
                            myDataGridView.Columns[1].DefaultCellStyle.Format = "yyyy-MM-dd hh:mm:ss.fffffff";
                catch (Exception ex)
Member 13694735 7-Jun-23 14:37pm    
var d = (DateTime)Reader["CreationDateTime"];
var dd = d.ToString("MM/dd/yyyy hh:mm:ss.fffffff tt");


This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900