Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compare datetime values just by date

Tags:

c#

i wish to compare to datetime values just by date, not by hour. How can i do so ?

I want to remove some values that are outside an interval selected by me :

if (DateTime.Compare(DateTime.Parse(t.Rows[i][1].ToString().Trim()), dateTimePicker1.Value) < 0 || DateTime.Compare(DateTime.Parse(t.Rows[i][1].ToString().Trim()), dateTimePicker2.Value) > 0) 
/*remove comand*/
like image 755
Alex Avatar asked Dec 08 '10 08:12

Alex


People also ask

Can we compare date with DateTime in SQL?

The right way to compare date only values with a DateTime column is by using <= and > condition. This will ensure that you will get rows where date starts from midnight and ends before midnight e.g. dates starting with '00:00:00.000' and ends at "59:59:59.999".

How can I compare only date parts in SQL Server?

To compare dates without the time part, don't use the DATEDIFF() or any other function on both sides of the comparison in a WHERE clause. Instead, put CAST() on the parameter and compare using >= and < operators. Let's use StackOverflow database to find all user profiles created on a particular date.


2 Answers

Use the DateTime.Dateproperty for this, since this contains only the date part of the DateTimeobject.

if (DateTime.Compare(DateTime.Parse(t.Rows[i][1].ToString().Trim()).Date,
    dateTimePicker1.Value.Date) < 0 || DateTime.Compare(DateTime.Parse(t.Rows[i]1].ToString().Trim()).Date, 
    dateTimePicker2.Value.Date) > 0)
like image 145
Øyvind Bråthen Avatar answered Sep 22 '22 14:09

Øyvind Bråthen


Be also aware of Utc and Locale issue. For me it's important to do all compare in Utc !

So do something like

Datetime d1, d2;
d1 = d1.toUniversalTime().Date;
d2 = d2.toUniversalTime().Date;
if(DateTime.Compare(d1, d2))....
like image 41
ykatchou Avatar answered Sep 19 '22 14:09

ykatchou