ChathurawinD
ChathurawinD

Reputation: 784

Compare date string with current date?

I'm reading a date value from a sql data reader to a string data type variable like this.

electionPosDate = Convert.ToDateTime(reader["elecPODate"]).ToString("dd/MM/yyyy");

How can I compare it with current system date in an if condition ?

if(electionPosDate==_____?)
{

}

Upvotes: 3

Views: 9209

Answers (2)

Soner Gönül
Soner Gönül

Reputation: 98868

Since electionPosDate is a string, not a DateTime, you need to compare it like;

if(electionPosDate == DateTime.Now.ToString("dd/MM/yyyy"))

But more important, I feel you are doing something wrong. If elecPODate column is already datetime typed, you can just use SqlDataReader.GetDateTime method to get the value as a DateTime. In your case, you are parsing your string to DateTime and after that, you convert it to string again. This is totally unnecessary. You should always choose the best column type that fits your data types.

For example, if this elecPODate column is the first column or your reader, you can just use;

DateTime electionPosDate = reader.GetDateTime(0);

and compare it like;

if(electionPosDate.Date == DateTime.Now.Date)

Please read: Bad habits to kick : choosing the wrong data type

Upvotes: 7

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62498

Use Date property of DateTime, if you want to check for Date part only, and for getting current date use DateTime.Now, but for only date part use DateTime.Now.Date:

DateTime electionPosDate = Convert.ToDateTime(reader["elecPODate"]);   
if(electionPosDate.Date ==DateTime.Now.Date)
{

}

See MSDN docs for Date and DateTime.Now

Upvotes: 5

Related Questions