开发者

compare datetime values just by date

开发者 https://www.devze.com 2023-01-29 16:07 出处:网络
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 :

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*/


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))

Do not forget to check about the UTC or timestamp value if exists.


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))....


DateTime d1, d2';

...

// following will compare by date and time both
d1 == d2

// following will compare by date only
d1.Date == d2.Date


You can use the Date property like this:

DateTime currentTime = Datetime.Now;
DateTime aBitEarlier = currentTime.AddHours(-5).AddMinutes(-4);

if (currentTime.Date == aBitEarlier.Date)
{
    ...
}

So in your case:

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)
{
    ...
}
0

精彩评论

暂无评论...
验证码 换一张
取 消