I want to compare between two dates.
From both the dates, I am fetching only date component using ToShortDateString(), as shown below. Now the problem is when I’m comparing the two dates. Its throwing error —
“Operator >= can’t be applied to operands of type string and string.”
DateTime srtdate = Convert.ToDateTime(allitem["StartDate"].Text.ToString());
DateTime srtdate = Convert.ToDateTime(allitem["StartDate"].Text.ToString());
(DateTime.Now.ToShortDateString() >= srtdate.ToShortDateString())
I need to compare date component only, NOT date and time together.
Please suggest what is the alternative way. Thanks
To JON:-
(I went tyhrough all what you explained and understood hopefully what the point actually you trying to make. Just to clarify more and make a last check I ll show an example.)
I have an web interface, where I give a start date and end date for a XYZ name (Note I can enter only date here, not time).
Start Date – 22-Feb-2012 AND End Date – 22-Feb-2012
Now in back end (code), if Start date and End date is same as Current date OR current date is in between start and end date, I want a ACTIVE flag set or else not. I give the condition as this:-
if ((DateTime.Today >= strdate.Date) && (DateTime.Today <= enddate.Date))
lblCondition.Text = "CHECKED";
Now when I debug the code,
Both DateTime.Today and strdate.Date gives the value as 2/22/2012 12:00:00 AM.
So, Jon my question is:- Would ‘today’ and ‘date’ work as per mentioned requirement, where only date component used. I hope it would.
Thanks a lot for all your explanantion before.
Why are you converting to a string representation at all? If you only want to compare the date parts to two
DateTimevalues, just use theDateproperty on each of them:And the
Todayproperty is equivalent toDateTime.Now.Date.Both
DateandTodaystrip off the time part, leaving a time of midnight. It’s not ideal that you’ve still got a type which is capable of representing times, but that’s just the way theDateTimeAPI works 🙁Note that you should usually avoid using
DateTime.NoworDateTime.Todayin web applications unless you’re really comfortable with it using the system default time zone as the day boundary. The user’s idea of “today” may not be the same as the server’s.You should avoid using string conversions unless your goal is really to get a text representation.
Of course another alternative would be to use the date/time library I’m building, Noda Time, where you could use a
LocalDatetype – obviously that makes it clearer that you’re only interested in the date and not the time.EDIT: As the OP seems unconvinced that
Datereally does ignore the time component, here’s an example: