問題:Linq中比較兩個時間的年月日部分
表中某個字段的時間和系統時間比較大小(只比較年月日)
思路一:轉換成字符串比較
var queryable = dbContext.Table .Where(p => p.ETime.ToString("yyyy-MM-dd") >= DateTime.Now.ToString("yyyy-MM-dd")
異常:字符串無法比較
思路二:先轉換成字符串,再轉換成DataTime比較
var queryable = dbContext.Table .Where(p => Convert.ToDateTime(p.ETime.ToString("yyyy-MM-dd")) >= Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd"))
異常:調用ToDateTime方法失敗
思路三:當前時間和系統時間(系統時間轉換成僅包含年月日)
DateTime dtToday = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd")); var queryable = dbContext.Table .Where(p => p.ETime >= dtToday)
Sqlserver中按日期的年月日比較:
CONVERT(varchar(12),v.ETime,112)>=CONVERT(varchar(12),GETDATE(),112)
http://blog.csdn.net/quxiao2002/article/details/7360542
本月內+今天
private DateTime dtMonthFirstday = Convert.ToDateTime(new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).ToString("yyyy-MM-dd"));
private DateTime dtToday = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd"));
private DateTime dtNexDay = Convert.ToDateTime(DateTime.Now.AddDays(1).ToString("yyyy-MM-dd"));
--今天
Where(p => p.Created >= dtToday && p.Created < dtNexDay).Count();
當月
Where(p => p.Created >= dtMonthFirstday).Count();
