roslynator icon indicating copy to clipboard operation
roslynator copied to clipboard

Feature request: Add analyzer for when DateTime is being assigned to a DateTimeOffset

Open omccully opened this issue 3 months ago • 0 comments

// simulate reading a UTC DateTime value from a database
// 9/30/2025 3:42:29 PM
DateTime utcNow = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Unspecified);

// implicitly convert it to an offset, it sets it to a value with a different meaning
// 9/30/2025 3:42:29 PM -05:00
DateTimeOffset offset = utcNow;

The DateTimeOffset is set to a value that assumes that the utcNow is in the local timezone, even though DateTimeKind is unspecified. This often can happen when reading the DateTime value from a database.

This implicit conversion probably should have never been created and it should be a compile warning, but as an alternative safety measure, I think there should be an analyzer warning for this. I've seen discussion about this implicit conversion issue before somewhere as well, but I can't find it.

I bring up this issue because this did lead to a production issue for me.

https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.op_implicit?view=net-9.0

omccully avatar Sep 30 '25 15:09 omccully