简体   繁体   English

从 DateTime 切换到 DateTimeOffset 时需要注意什么?

[英]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.我正在考虑切换到 DateTimeOffset 以获得一些未来的功能,我只是想确保我当前编写的代码不会因此而中断。 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. PS:也是的,我对 C# 很陌生,所以我很感激对我不了解某些事情的一些理解。

DateTimeOffset is the amount of time that has passed since datetime x. DateTimeOffset是自日期时间 x 以来经过的时间量。 DateTime is an exact date and time (in a certain timezone). DateTime是一个确切的日期和时间(在某个时区)。

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).您还可以使用绝对版本的 TimeSpans(日期 x 和日期 y 之间的差异为 16 小时)。

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有关更多信息/示例,请参阅 MSDN: 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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