Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

}
like image 609
ChathurawinD Avatar asked Sep 01 '26 13:09

ChathurawinD


2 Answers

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

like image 176
Soner Gönül Avatar answered Sep 04 '26 03:09

Soner Gönül


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

like image 36
Ehsan Sajjad Avatar answered Sep 04 '26 02:09

Ehsan Sajjad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!