snippetcsharpMajor
Convert Object to a DateTime
Viewed 0 times
convertobjectdatetime
Problem
public static DateTime ObjectToDateTime(object o, DateTime defaultValue)
{
if (o == null) return defaultValue;
DateTime dt;
if (DateTime.TryParse(o.ToString(), out dt))
return dt;
else
return defaultValue;
}The code feels too wordy and smells bad. Is there a better way?
Solution
On the offhand chance that your object is already a
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
There we go, 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("CreatedDate");There we go, a
DateTime?, no coding of a conversion necessary. You can even specify a default and type if to DateTimevar createdDate = row.Field("CreatedDate").GetValueOrDefault(DateTime.Now);
var createdDate = row.Field("CreatedDate") ?? DateTime.Now;Code Snippets
if (o is DateTime)
return (DateTime)o;var createdDate = row.Field<DateTime?>("CreatedDate");var createdDate = row.Field<DateTime?>("CreatedDate").GetValueOrDefault(DateTime.Now);
var createdDate = row.Field<DateTime?>("CreatedDate") ?? DateTime.Now;Context
StackExchange Code Review Q#3879, answer score: 31
Revisions (0)
No revisions yet.