我正在尝试比较来自传入请求的时间戳和数据库存储值。当然,SQL Server在时间上保持一些毫秒的精度,当读取到. net DateTime时,它包含了这些毫秒。但是,传入系统的请求不能提供这样的精度,所以我只需要去掉毫秒。
我觉得我遗漏了一些明显的东西,但我还没有找到一种优雅的方法来做到这一点(c#)。
我正在尝试比较来自传入请求的时间戳和数据库存储值。当然,SQL Server在时间上保持一些毫秒的精度,当读取到. net DateTime时,它包含了这些毫秒。但是,传入系统的请求不能提供这样的精度,所以我只需要去掉毫秒。
我觉得我遗漏了一些明显的东西,但我还没有找到一种优雅的方法来做到这一点(c#)。
当前回答
2上述解决方案的扩展方法
public static bool LiesAfterIgnoringMilliseconds(this DateTime theDate, DateTime compareDate, DateTimeKind kind)
{
DateTime thisDate = new DateTime(theDate.Year, theDate.Month, theDate.Day, theDate.Hour, theDate.Minute, theDate.Second, kind);
compareDate = new DateTime(compareDate.Year, compareDate.Month, compareDate.Day, compareDate.Hour, compareDate.Minute, compareDate.Second, kind);
return thisDate > compareDate;
}
public static bool LiesAfterOrEqualsIgnoringMilliseconds(this DateTime theDate, DateTime compareDate, DateTimeKind kind)
{
DateTime thisDate = new DateTime(theDate.Year, theDate.Month, theDate.Day, theDate.Hour, theDate.Minute, theDate.Second, kind);
compareDate = new DateTime(compareDate.Year, compareDate.Month, compareDate.Day, compareDate.Hour, compareDate.Minute, compareDate.Second, kind);
return thisDate >= compareDate;
}
用法:
bool liesAfter = myObject.DateProperty.LiesAfterOrEqualsIgnoringMilliseconds(startDateTime, DateTimeKind.Utc);
其他回答
DateTime d = DateTime.Now;
d = d.AddMilliseconds(-d.Millisecond);
关于糖尿病反应。这对我来说是可行的,除了我必须在乘法之前使用Floor来去除除法的小数部分。所以,
d = new DateTime((d.Ticks / TimeSpan.TicksPerSecond) * TimeSpan.TicksPerSecond);
就变成了
d = new DateTime(Math.Floor(d.Ticks / TimeSpan.TicksPerSecond) * TimeSpan.TicksPerSecond);
我本希望两个Long值的除法结果是Long,从而去掉小数部分,但它将其解析为Double,在乘法之后保留完全相同的值。
埃普西
不是最快的解决方案,但简单易懂:
DateTime d = DateTime.Now;
d = d.Date.AddHours(d.Hour).AddMinutes(d.Minute).AddSeconds(d.Second)
DateID.Text = DateTime.Today.ToShortDateString();
Use ToShortDateString() //Date 2-02-2016
Use ToShortDateString() // Time
并通过使用
ToLongDateString() // its show 19 February 2016.
:P
2上述解决方案的扩展方法
public static bool LiesAfterIgnoringMilliseconds(this DateTime theDate, DateTime compareDate, DateTimeKind kind)
{
DateTime thisDate = new DateTime(theDate.Year, theDate.Month, theDate.Day, theDate.Hour, theDate.Minute, theDate.Second, kind);
compareDate = new DateTime(compareDate.Year, compareDate.Month, compareDate.Day, compareDate.Hour, compareDate.Minute, compareDate.Second, kind);
return thisDate > compareDate;
}
public static bool LiesAfterOrEqualsIgnoringMilliseconds(this DateTime theDate, DateTime compareDate, DateTimeKind kind)
{
DateTime thisDate = new DateTime(theDate.Year, theDate.Month, theDate.Day, theDate.Hour, theDate.Minute, theDate.Second, kind);
compareDate = new DateTime(compareDate.Year, compareDate.Month, compareDate.Day, compareDate.Hour, compareDate.Minute, compareDate.Second, kind);
return thisDate >= compareDate;
}
用法:
bool liesAfter = myObject.DateProperty.LiesAfterOrEqualsIgnoringMilliseconds(startDateTime, DateTimeKind.Utc);