我正在尝试比较来自传入请求的时间戳和数据库存储值。当然,SQL Server在时间上保持一些毫秒的精度,当读取到. net DateTime时,它包含了这些毫秒。但是,传入系统的请求不能提供这样的精度,所以我只需要去掉毫秒。

我觉得我遗漏了一些明显的东西,但我还没有找到一种优雅的方法来做到这一点(c#)。


当前回答

我知道答案很晚了,但是摆脱毫秒的最好方法是

var currentDateTime = DateTime.Now.ToString("s");

尝试打印变量的值,它将显示日期时间,没有毫秒。

其他回答

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);

我知道答案很晚了,但是摆脱毫秒的最好方法是

var currentDateTime = DateTime.Now.ToString("s");

尝试打印变量的值,它将显示日期时间,没有毫秒。

四舍五入:四舍五入到第二:

dateTime.AddTicks(-dateTime.Ticks % TimeSpan.TicksPerSecond)

替换为TicksPerMinute以四舍五入到分钟。


如果您的代码对性能敏感,请谨慎处理

new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second)

我的应用在System.DateTime.GetDatePart中花费了12%的CPU时间。

你可以简单地使用Split

 new TimeSpan(new DateTime(1970, 1, 1).Ticks).TotalSeconds.ToString().Split('.')[0]

下面是一个基于之前答案的扩展方法,它可以让你截断到任何分辨率…

用法:

DateTime myDateSansMilliseconds = myDate.Truncate(TimeSpan.TicksPerSecond);
DateTime myDateSansSeconds = myDate.Truncate(TimeSpan.TicksPerMinute)

类:

public static class DateTimeUtils
{
    /// <summary>
    /// <para>Truncates a DateTime to a specified resolution.</para>
    /// <para>A convenient source for resolution is TimeSpan.TicksPerXXXX constants.</para>
    /// </summary>
    /// <param name="date">The DateTime object to truncate</param>
    /// <param name="resolution">e.g. to round to nearest second, TimeSpan.TicksPerSecond</param>
    /// <returns>Truncated DateTime</returns>
    public static DateTime Truncate(this DateTime date, long resolution)
    {
        return new DateTime(date.Ticks - (date.Ticks % resolution), date.Kind);
    }
}