DateTime比较没有时间部分?

时间:2012-07-24 06:50:12

标签: c# .net linq datetime date-comparison

我写了这段代码。但是我想忽略时间,我只想比较一天。

from s in sayac_okumalari
where s.okuma_tarihi == startDate && s.sayac_id == sayac_id
group s by new { date = new DateTime(((DateTime)s.okuma_tarihi).Year, ((DateTime)s.okuma_tarihi).Month, ((DateTime)s.okuma_tarihi).Day, ((DateTime)s.okuma_tarihi).Hour, 1, 1) } into g
select new
{
     okuma_tarihi = g.Key.date,
     T1 = g.Sum(x => x.toplam_kullanim_T1),
     T2 = g.Sum(x => x.toplam_kullanim_T2),
     T3 = g.Sum(x => x.toplam_kullanim_T3)
};

例如:

25.02.1987 == 25.02.1987

5 个答案:

答案 0 :(得分:17)

使用s.okuma_tarihi.Value.Date == startDate.Date。这应该允许您仅比较日期组件。

更新从评论中的讨论看,用户正在使用NullableType。因此更新了NullableType的解决方案。

答案 1 :(得分:7)

使用DateTime的Date属性。例如,

var date= DateTime.Now.Date;

答案 2 :(得分:2)

因为您可以将s.okuma_tarihi转换为DateTime,我认为您可以这样做:

var sonuc = from s in sayac_okumalari
        where (DateTime)s.okuma_tarihi.Date == startDate.Date && s.sayac_id == sayac_id
        group s by new { date = new DateTime(((DateTime)s.okuma_tarihi).Year, ((DateTime)s.okuma_tarihi).Month, ((DateTime)s.okuma_tarihi).Day, ((DateTime)s.okuma_tarihi).Hour, 1, 1) } into g
        select new
        {
             okuma_tarihi = g.Key.date,
             T1 = g.Sum(x => x.toplam_kullanim_T1),
             T2 = g.Sum(x => x.toplam_kullanim_T2),
             T3 = g.Sum(x => x.toplam_kullanim_T3)
        };

希望它有所帮助。

答案 3 :(得分:0)

试试这个......

        try
        {
         DateTime Date1= DateTime.ParseExact(txtBox1.Text,"dd/MM/yyyy",null);
         DateTime Date2 = DateTime.ParseExact(txtBox2.Text, "dd/MM/yyyy", null);

          if (Date1 > Date2) 
          {
           //........
          }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

答案 4 :(得分:0)

尝试使用DateTime对象上的Date属性将是一个很好的简单解决方案。

string AdmissionDate = "10/15/2017" // mm/dd/yyyy
string DepartureDate = "10/14/2017" // mm/dd/yyyy

if (Convert.ToDateTime(AdmissionDate).Date > Convert.ToDateTime(DepartureDate).Date)
{
    // Validation: Admission Date can not be greater than Departure Date... 
}