C # Precision and rounding precision DateTime

I have two dates. One is user-provided and accurate for the second and one of the database and accurate to the tick level. This means that both of them represent 11/13/2009 17:22:17 (UK dates)

userTime == dbTime 

returns false

Tick ​​values: 633937297368344183 and 633937297370000000.

To fix this, I use code

userTime = new DateTime(
                userTime.Year, 
                userTime.Month, 
                userTime.Day, 
                userTime.Hour, 
                userTime.Minute, 
                userTime.Second);

dbTime = new DateTime(
                dbTime.Year, 
                dbTime.Month, 
                dbTime.Day, 
                dbTime.Hour, 
                dbTime.Minute, 
                dbTime.Second);

Is there a more elegant way to achieve this?

+3
source share
5 answers

The most obvious refactoring would be to remove duplication:

public static DateTime TruncateToSecond(DateTime original)
{
    return new DateTime(original.Year, original.Month, original.Day,
        original.Hour, original.Minute, original.Second);
}

...
if (TruncateToSecond(userTime) == TruncateToSecond(dbTime))
    ...

You could very well write:

if (userTime.Ticks / TimeSpan.TicksPerSecond
    == dbTime.Ticks / TimeSpan.TicksPerSecond)
   ...

I believe this will work, simply because checkmark 0 is at the beginning of the second.

, . , DateTimeOffset.

+8

UserDateTime.Substract(dbDateTime).TotalSeconds == 0
+4

TimeSpan. ( , , ) , 0,002.

TimeSpan delta = dt1 - dt2;

// get the delta as an absolute value:
if (delta < new TimeSpan(0, 0, 0))
    delta = new TimeSpan(0, 0, 0) - delta;

// My threshold is 1 second.  The difference can be no more than 1 second. 
TimeSpan threshold = new TimeSpan(0, 0, 1);

if (delta > threshold)
{
    // error...
}
+1

Cheeso. DateTime, :

public static bool IsSimilarTo(this DateTime thisDateTime, DateTime otherDateTime, TimeSpan tolerance)
{
    DateTime allowedMinimum = thisDateTime.Subtract(tolerance);
    DateTime allowedMaximum = thisDateTime.Add(tolerance);

    if (otherDateTime < allowedMinimum || otherDateTime > allowedMaximum)
    {
        return false;
    }

    return true;
}

, : -)

+1

Microsoft.VisualBasic,

  DateTime a = new DateTime(633937297368344183L);
  DateTime b = new DateTime(633937297370000000L);

  Console.WriteLine(Microsoft.VisualBasic.DateAndTime.DateDiff(DateInterval.Second, a, b,FirstDayOfWeek.Sunday ,FirstWeekOfYear.System) == 0); //true

, # FirstDayOfWeek FirstWeekOfYear.

VB.net

0

Source: https://habr.com/ru/post/1723348/


All Articles