chathwind chathwind - 3 months ago 17
C# Question

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==_____?)
{

}

Answer

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