简体   繁体   中英

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

}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM