如何查询linq检查日期是在月,四季或一年 [英] How to make a query linq check date is in month, quarter or a year

查看:125
本文介绍了如何查询linq检查日期是在月,四季或一年的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有 userdateregistered 字段的用户表,并希望显示在当前月份,上个月,当前季度,最后四分之一,当年和去年的用户注册(日期参考是datetime.now)。我需要建立一个linq查询

I have a User table with userdateregistered field, and want to show User registered in the current month, last month, current quarter, last quarte, current year and last year (date reference is datetime.now).I need to build a linq query

例如:

2013 / 12/31如果是在12月(12)的月份

2013/12/31 if is in the month December(12)

2012/01/15如果在第一季度(1)

2012/01/15 if is in the first quarter (1)

2013/05/12如果是在2012年。

2013/05/12 if is in the year 2012.

推荐答案

这是查询选择全部来自当前月份的用户

Here is query which select all users from current month

DateTime startOfMonth = DateTime.Today.AddDays(1 - DateTime.Today.Day);
DateTime today = DateTime.Today;

var users =
   from u in context.Users
   where EntityFunctions.TruncateTime(u.UserDateRegistered) >= startOfMonth &&
         EntityFunctions.TruncateTime(u.UserDateRegistered) <= today
   select u;

它显示了按日期过滤的想法。只需计算适当的开始和结束日期。并使用 EntityFunctions.TruncateTime 方法仅比较日期。

It shows you idea of filtering by date. Just calculate appropriate begin and end dates. And use EntityFunctions.TruncateTime method to compare only dates.

实际上,我创建了用于保存开始和结束日期的类 DateRange ,创建一些范围:

Actually I'd created class DateRange for holding begin and end dates, and creating some ranges:

public class DateRange
{
    public DateTime BeginDate { get; set; }
    public DateTime EndDate { get; set; }

    public static DateRange OfYear(int year)
    {
        return new DateRange
        {
            BeginDate = new DateTime(year, 1, 1),
            EndDate = new DateTime(year, 12, 31)
        };
    }

    public static DateRange OfMonth(int month)
    {
        var year = DateTime.Today.Year;

        return new DateRange
        {
            BeginDate = new DateTime(year, month, 1),
            EndDate = new DateTime(year, month, 1).AddMonths(1).AddDays(-1)
        };
    }
}

它将允许您轻松创建过滤器范围: / p>

It will allow you to create filter ranges easily:

var range = DateRange.OfMonth(10);
var users =
   from u in context.Users
   where EntityFunctions.TruncateTime(u.UserDateRegistered) >= range.BeginDate &&
         EntityFunctions.TruncateTime(u.UserDateRegistered) <= range.EndDate
   select u;     

这篇关于如何查询linq检查日期是在月,四季或一年的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆