I'm new to c#.
I've an SQLite table containing "marketDate" field (datatype Date) and I'm using SQLiteDataReader.
I need to build a string this way: MONDAY 2016-01-03
So far I've found 2 ways of doing it:
1)
myString = (DateTime.Parse(reader["marketDate"].ToString())).ToString("dddd").ToUpper() + " " + (DateTime.Parse(reader["marketDate"].ToString())).ToShortDateString();
2)
myString = ((DateTime)reader["marketDate"]).ToString("dddd").ToUpper() + " " + ((DateTime)reader["marketDate"]).ToShortDateString();
I'd like to know which is the best way of doing it (best practice), and I'd really appreciate if someone will explain me the differences beetween the 2 approaches datetime.parse and (datetime)object). I couldn't find any info about the second one.
Thanks
This:
DateTime.Parse(reader["marketDate"].ToString())
gets the date from the reader (reader["marketDate"]
). The result is of type DateTime
.
This DateTime is converted to a string (.ToString()
).
This string is converted back to a DateTime (DateTime.Parse(...)
).
As you can see, steps 2 and 3 are redundant and can be omitted. Which is exactly what your second code example does:
(DateTime)reader["marketDate"]
reader["marketDate"]
). This is currently of type DateTime
, but the compiler does not know that yet (since reader's indexer returns the supertype object). Thus, we tell that compiler that we know this is a DateTime
by explicitly casting it. This allows us to call DateTime-specific methods on it.Since you asked about best practice: Your second example is better than the first one. However, my preferred solution would be to use SQLiteDataReader.GetDateTime:
reader.GetDateTime("marketDate")