On the offhand chance that your object is already a DateTime
, you're performing unnecessary conversions to and from strings.
if (o is DateTime)
return (DateTime)o;
This also strikes me as something you might be doing for a database item, for example. In which case, I'd encourage you to know and trust your data types and then use existing methods of retrieval.
For example, if you have a DataTable
with a column CreatedDate
, you should know it's a date, what you might not know is if it has a value if the column is nullable at the database. That's fine, you can handle that in code.
var createdDate = row.Field<DateTime?>("CreatedDate");
There we go, a DateTime?
, no coding of a conversion necessary. You can even specify a default and type if to DateTime
var createdDate = row.Field<DateTime?>("CreatedDate").GetValueOrDefault(DateTime.Now);
var createdDate = row.Field<DateTime?>("CreatedDate") ?? DateTime.Now;
DateTime
is a value type and thus could not be used with theas
operator nor set tonull
. That would be invalid code. \$\endgroup\$as
keyword. A failed conversion cannot be set to null. However, if you use aDateTime?
(nullable DateTime) instead, your code would work. \$\endgroup\$ToString()
on an object you might be losing some information depending on the DateTime format (for example the milliseconds part). I.e.o.ToString() = "19/06/2017 14:17:04"
but((DateTime)o).ToString("o") = 2017-06-19T14:17:04.0393053+02:00
. \$\endgroup\$