Question

I'd like to format all of my dates to something like dd-MM-yyyy but can't seem to get it to work. All of the columns below that use OracleDataReader.GetDateTime are DATE fields in the DB.

OracleDataReader reader = command.ExecuteReader();
while (reader.Read())
{
   myDetails detail = new myDetails();
   detail.ColumnA = reader.GetDecimal(0);
   detail.ColumnB = reader.GetString(1);
   detail.ColumnC = reader.GetDecimal(2);
   detail.ColumnD = reader.GetDateTime(3);
   detail.ColumnE = reader.GetDecimal(4);
   detail.ColumnF = reader.GetDateTime(5);
   detail.ColumnG = reader.GetDateTime(6);
   detail.ColumnH = Convert.ToChar(reader.GetString(7));
   detail.ColumnI = reader.GetDateTime(8);
   details.Add(detail);
}
reader.Close();

I've tried the following but each give me errors:

detail.ColumnD = reader.GetDateTime(3).ToString('dd-MM-yyyy');
detail.ColumnD = reader.GetDateTime(3).Parse('dd-MM-yyyy');
detail.ColumnD = reader.GetDateTime(3).TryParse('dd-MM-yyyy');
detail.ColumnD = DateTime.Parse(3).ToString('dd-MM-yyyy');
detail.ColumnD = reader.GetDateTime(3).ToLongDateString('dd-MM-yyyy');

Any idea what could be wrong?

Was it helpful?

Solution

detail.ColumnD is probably a DateTime type. DateTime has no format. You format a DateTime when you convert it to a string. So after you've done:

detail.ColumnD = reader.GetDateTime(8); 

Do:

Console.WriteLine("ColumnD: "+detail.columnD.ToString("dd-MM-yyyy"));

This will allow you to see the difference. So anywhere you want to actually display detail.ColumnD in the UI, convert it to a string and pass in the necessary format string. For example, see below.

DateTime dt=DateTime.Now;
TextBox tb=new TextBox();
tb.Text=dt.ToString("dd-MM-yyyy");

For those that find this question via a web search, you can change the date format to any other valid format string. There are several pre-defined ones or you can do custom ones. See Custom Date And Time Format Strings in MSDN Documentation.

For a deeper understanding, the DateTime object actually just stores the number of ticks (100 nanosecond units) since midnight on January 1st of 0001 Common Era. DateTime has convenience methods that understand how to convert from a string (Parse or TryParse) or to a string. See DateTime documentation in MSDN for more details.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top