Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net error: Unable to cast object of type 'System.DateTime' to type 'System.String'

Sorry, but this is a brain phart. I have searched the whole internet, but can't figure this out.
Error: "Unable to cast object of type 'System.DateTime' to type 'System.String'."

if (oDbDataReader.GetString(2) == DateTime.Now.AddDays(-90).ToShortDateString())       //DateCreated
{
    oEmp.PasswordCompliance = "Password expired";
}
like image 741
DNR Avatar asked Jan 16 '23 03:01

DNR


2 Answers

Two problems, first you are comparing for equality, if anyone checks after 3 months this will not trigger. Second, you probably are storing a Date or DateTime in you database, causing your call to GetString to fail.

Use the following instead (no reason to do use strings in this case).

if (oDbDataReader.GetDateTime(2) <= DateTime.Now.AddDays(-90))

Also note that your original had an extra ; potentially causing your password to always be expired.

like image 162
Guvante Avatar answered Jan 20 '23 02:01

Guvante


What is the type of the column [2]? If it is DateTime you should try DbDataReader.GetDateTime

if (oDbDataReader.GetDateTime(2) < DateTime.Now.AddDays(-90)) 
{
    oEmp.PasswordCompliance = "Password expired";
}
like image 26
oleksii Avatar answered Jan 20 '23 00:01

oleksii