我正在尝试比较来自传入请求的时间戳和数据库存储值。当然,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);

其他回答

在我的情况下,我的目标是从datetimePicker工具保存TimeSpan,而不节省秒和毫秒,这里是解决方案。

首先转换datetimePicker。值转换为你想要的格式,我的格式是“HH:mm”,然后将其转换回TimeSpan格式。

var datetime = datetimepicker1.Value.ToString("HH:mm");
TimeSpan timeSpan = Convert.ToDateTime(datetime).TimeOfDay;
DateID.Text = DateTime.Today.ToShortDateString();

Use ToShortDateString() //Date 2-02-2016
Use ToShortDateString() // Time 

并通过使用

ToLongDateString() // its show 19 February 2016.

:P

新方法

String Date = DateTime.Today.ToString("dd-MMM-yyyy"); 

//定义字符串传递参数dd-mm -yyyy返回24-feb-2016

或显示在文本框上

txtDate.Text = DateTime.Today.ToString("dd-MMM-yyyy");

//加载pagonload

以下将适用于具有分数毫秒的DateTime,并保留Kind属性(Local, Utc或Undefined)。

DateTime dateTime = ... anything ...
dateTime = new DateTime(
    dateTime.Ticks - (dateTime.Ticks % TimeSpan.TicksPerSecond), 
    dateTime.Kind
    );

或等价的或更短的:

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

这可以推广为一个扩展方法:

public static DateTime Truncate(this DateTime dateTime, TimeSpan timeSpan)
{
    if (timeSpan == TimeSpan.Zero) return dateTime; // Or could throw an ArgumentException
    if (dateTime == DateTime.MinValue || dateTime == DateTime.MaxValue) return dateTime; // do not modify "guard" values
    return dateTime.AddTicks(-(dateTime.Ticks % timeSpan.Ticks));
}

使用方法如下:

dateTime = dateTime.Truncate(TimeSpan.FromMilliseconds(1)); // Truncate to whole ms
dateTime = dateTime.Truncate(TimeSpan.FromSeconds(1)); // Truncate to whole second
dateTime = dateTime.Truncate(TimeSpan.FromMinutes(1)); // Truncate to whole minute
...

与其放弃毫秒然后比较,为什么不比较差异呢?

DateTime x; DateTime y;
bool areEqual = (x-y).TotalSeconds == 0;

or

TimeSpan precision = TimeSpan.FromSeconds(1);
bool areEqual = (x-y).Duration() < precision;