-
Notifications
You must be signed in to change notification settings - Fork 4.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
System.DateTime.AddDays() adds additional tick #98305
Comments
Tagging subscribers to this area: @dotnet/area-system-datetime Issue DetailsDescriptionRunning the following code:
results in 638431426870000000 on .NET 6 (as expected) Configuration.NET 7 and .NET 8 Regression?Worked .NET <= 6
|
Likely just floating point precision. We have become more compliant since .NET Framework and that sometimes gives results that look less correct, but round trip correctly. |
Yes, this is a published breaking change https://learn.microsoft.com/en-us/dotnet/core/compatibility/core-libraries/7.0/datetime-add-precision. |
To help explain the why for this particular example, Thus, So you aren't subtracting If you want precision here, you should avoid |
Hm. Okay... Another proof is that I already have an alternative implementation of AddDays(). I wrote that for another reason (to limit the result instead of throwing an exception in case of an overflow). That implementation had the full resolution since it existed and never had that "1 tick issue" for small numbers of days. My guess is that the current implementation is also highly optimized which leads to that fault...sorry: breaking change. |
Truncation is indeed used by default, because that's how But even if rounding were done, it would still lead to bugs and unexpected behaviors for users in other cases. Consider that Depending on the exact value used and the exact tick counts involved, you may end up just over or just under what you intended. As much as rounding would fix this particular case, it would inversely break another users case (and we've had past issues where such a scenario cropped up and we had to explain it there as well). The best practice here is really to just not use non-integral values.
If you're taking in |
So what are methods to add time spans with integers? |
We have #93890 which addressing the TimeSpan issues. |
Notably in addition to the new APIs which will cover explicitly passing in integers. Integers up to 2^53 are exactly representable as |
Description
Running the following code:
new DateTime(2024, 2, 11, 11, 6, 7).AddDays(-1.2).Ticks
results in 638431426870000000 on .NET 6 (as expected)
but 638431426870000001 on .NET 7 and 8!
Configuration
.NET 7 and .NET 8
Regression?
Worked .NET <= 6
The text was updated successfully, but these errors were encountered: