简体   繁体   中英

Anything I need to look out for when switching from DateTime to DateTimeOffset?

I am considering switching to DateTimeOffset for some future functionality, I just want to make sure that the code I have currently written doesn't break by doing so. Are there any major differences in how these two are implemented, how they work especially when comparing two times to one-another (eg. larger/smaller than or equal to, which I use quite a lot as of now to confirm validity of certain data)?

Ideally, I could just change the names and it would work as it does now, just with the added benifit of having that offset data (if I've understood the difference correctly that is).

Thanks all.

PS: also yes, I'm quite new to C# so I'd appreceate some understanding for me not understanding certain things.

DateTimeOffset is the amount of time that has passed since datetime x. DateTime is an exact date and time (in a certain timezone).

They're different types, so you can't simply replace the one with the other. It will involve changing all the logic you've written about handling the variable.

If the issue you have is that you do a lot of math/comparisons between dates, you can substract dates to get an offset. You can also use TimeSpans which is an absolute version (The difference between date x and date y is 16 hours).

See MSDN for more info/examples: https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset?view=net-7.0 https://learn.microsoft.com/en-us/dotnet/api/system.timespan?view=net-7.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM