我有两个日期值,一个已存储在数据库中,另一个由用户使用DatePicker选择.用例是从数据库中搜索特定日期.
先前在数据库中输入的值始终具有12:00:00的时间分量,其中从选择器输入的日期具有不同的时间分量.
我只对日期组件感兴趣,并且想要忽略时间组件.
在C#中进行这种比较的方法有哪些?
另外,如何在LINQ中执行此操作?
更新:在LINQ to Entities上,以下工作正常.
e => DateTime.Compare(e.FirstDate.Value, SecondDate) >= 0
Run Code Online (Sandbox Code Playgroud) c# linq linq-to-entities entity-framework datetime-comparison
可能重复:
如何比较C#中的日期
我的这个代码:
public static string getLogFileNameForDate(DateTime dt)
{
if (dt.Equals(DateTime.Now))
Run Code Online (Sandbox Code Playgroud)
...即使两个日期相同(日期)也会失败,因为dt在启动时被分配了一个值(例如"6/18/2012 15:19:42"),因此日期不完全相同,甚至虽然年,月和日是相同的(DateTime.Now的值可能是,例如,"6/18/2012 15:30:13").
我知道我可以这样测试它:
if ((dt.Year.Equals(DateTime.Now.Year) && (dt.Month.Equals(DateTime.Now.Month) && (dt.Day.Equals(DateTime.Now.Day))
Run Code Online (Sandbox Code Playgroud)
......但这似乎有点像Jethro*
什么是接受/首选方法(没有双关语意)?
我的.net应用程序中有以下功能LINQ
public ActionResult Index()
{
Dictionary<DateTime?, List<Event>> result;
result = (from events in db.Events.Include("Activity")
where events.IsActive
group events by DbFunctions.TruncateTime(events.DateTimeFrom) into dateGroup
select new { EventDate = dateGroup.Key, Events = dateGroup.ToList() }).ToDictionary(x => x.EventDate, x => x.Events);
return View(result);
}
Run Code Online (Sandbox Code Playgroud)
当我在ASP .NET CORE中使用它时,我不能使用DbFunctions.我如何重写它以使其在Microsoft.EntityFrameworkCore中工作?我正在使用SQLite,如果这有所作为.
我写了这段代码.但我想忽略时间,我只想比较一天.
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)
};
Run Code Online (Sandbox Code Playgroud)
例如:
25.02.1987 == 25.02.1987
Run Code Online (Sandbox Code Playgroud) 如何在 C# 中的 DateTime 类型中仅比较日期而不比较时间。其中一个日期将为空。我该怎么做?
我试过这种方式,但出现错误。这是我的代码。
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
DateTime _dateJoin = DateTime.ParseExact(value.ToString(), "MM/dd/yyyy", null);
DateTime _CurDate = DateTime.ParseExact(DateTime.Now.ToString(), "MM/dd/yyyy", null);
int cmp = _dateJoin.CompareTo(_CurDate);
if (cmp > 0)
{
return ValidationResult.Success;
}
else if (cmp < 0)
{
return new ValidationResult(ErrorMessage);
}
else
{
return ValidationResult.Success;
}
}
Run Code Online (Sandbox Code Playgroud)
该值可变具有时间部分有效的日期太。谢谢
C#中是否有一个方法可以比较SQL DateDiff方法之类的日期,包括时间部分参数?
例如,我有两个日期:
DateTime early = "2013.02.01 07:31:15";
DateTime soon = "2013.02.01 23:48:35";
if (Compare(early, soon, DAY) == true)
{
//I want to be here
}
Run Code Online (Sandbox Code Playgroud)
我希望得到这两个对象在年,月和日相等的信息; 其余对我来说并不重要.