Alex A.
Alex A.

Reputation: 5586

MS Access Date/Time printing differently in C#

I have an Microsoft Access database with a table which looks like this in design view:

Field Name |  Data Type
-----------+-------------
ID         | Number
Name       | Text
Birthday   | Date/Time

When you view the table in Access, the values look like this:

ID  Name   Birthday
----------------------
1   Jose   9/19/1948
2   Mark   10/1/2001
3   Cindy  3/14/1987

I imported the Access table to a C# DataTable object using OLEDB. When I go to print out the values, the dates display differently.

OleDbCommand selectTable = new OleDbCommand("SELECT * FROM [Example]", conn);
// conn is my OLEDB connection object

OleDbDataReader oleReader = selectTable.ExecuteReader();

DataTable currentTable = new DataTable();

currentTable.Load(oleReader);

foreach (DataRow row in currentTable)
{
    foreach (DataColumns col in currentTable)
    {
        Console.Write(row[col].ToString().Trim().PadRight(10));
    }
    Console.Write("\r\n");
}

This prints out

1         Jose      9/19/1948 12:00:00 AM
2         Mark      10/1/2001 12:00:00 AM
3         Cindy     3/14/1987 12:00:00 AM

Which is weird. Especially because I determined that the longest text representation of the numeric date/time values has only 10 characters (using the accepted method here, if it helps). Clearly the date values being written to the console have more than 10 characters. Can anyone provide some insight into what's going on here?

My goal is directly export the values from Access so that whatever value is stored in Access is what prints out. If a time portion is there I want to print it with the date and if not then I just want to print the date.

Upvotes: 0

Views: 172

Answers (2)

Martin Costello
Martin Costello

Reputation: 10843

You could use ToShortDateString() instead of ToString() to omitt the time.

Upvotes: 0

user27414
user27414

Reputation:

It's reading the date values as DateTime objects, which always contain a time component. When you print them, they are printing using the default ToString(). You can specify a format to print them any way you like (e.g., "MM/dd/yyyy").

Note that PadRight does not truncate at 10 characters, it pads up to ten characters.

Upvotes: 2

Related Questions