System.DateTime 和 System.DateTimeOffset 之间的区别
谁能解释 C#.NET 中 System.DateTime 和 System.DateTimeOffset 之间的区别?哪个最适合与来自不同时区的用户构建 Web 应用程序?
Can anyone explain the difference between System.DateTime and System.DateTimeOffset in C#.NET? Which is best suited for building web apps with users from different time zones?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
DateTime 值定义特定的日期和时间,它包括 Kind 属性,该属性提供有关该日期和时间所属时区的有限信息。
DateTimeOffset 结构表示日期和时间值,以及指示该值与 UTC 差异程度的偏移量。因此,该值始终明确标识单个时间点。
DateTimeOffset 应被视为应用程序开发的默认日期和时间类型,因为 DateTimeOffset 值的使用比 DateTime 值更常见。
查看更多信息、代码示例:
http://msdn.microsoft.com/en-us/library/bb384267.aspx
A DateTime value defines a particular date and time, it includes a Kind property that provides limited information about the time zone to which that date and time belongs.
The DateTimeOffset structure represents a date and time value, together with an offset that indicates how much that value differs from UTC. Thus, the value always unambiguously identifies a single point in time.
DateTimeOffset should be considered the default date and time type for application development as the uses for DateTimeOffset values are much more common than those for DateTime values.
See more info, code examples at:
http://msdn.microsoft.com/en-us/library/bb384267.aspx
这里有几点:
日期时间信息应以 UTC 格式存储在数据库中:
https://web.archive.org/web/20201202215446/http://www.4guysfromrolla.com/articles/081507-1.aspx
当您在 Web 应用程序中使用 DateTime 信息时您需要将其转换为 LocalTime:
将从 Web 服务器的角度将其转换为本地时间。
如果您在一个位置有一个 Web 服务器,为多个国家/地区的客户端提供服务,那么您将需要在客户端本身上使用 javascript 执行此操作:
http://www.java2s.com/Code/JavaScript/Date-Time/ConvertDatetoLocaleString.htm
There are a couple of point here:
DateTime information should be stored in UTC format in your database:
https://web.archive.org/web/20201202215446/http://www.4guysfromrolla.com/articles/081507-1.aspx
When you use DateTime information in your Web Application you will need to convert it to LocalTime:
will convert it to the local time from the Web Server's perspective.
If you have a WebServer in one location, serving clients in multiple countries, then you will need to perform this operation in javascript on the Client itself:
http://www.java2s.com/Code/JavaScript/Date-Time/ConvertDatetoLocaleString.htm
DateTimeOffset 将日期时间表示为 UTC 日期时间。
因此
与此处相同,
即使一个初始化为 DateTimeOffset.Now,另一个初始化为 DateTimeOffset.UTCNow,dtoNow 将等于 dtoUTCNow;
因此 DatetimeOffset 适合存储 UTC 的差异或偏移量。
有关详细信息,请参阅 MSDN。
DateTimeOffset represents the datetime as UTC datetime.
So
is same as
Here dtoNow will be equal to dtoUTCNow even though one was initialized to DateTimeOffset.Now and the other was initialize to DateTimeOffset.UTCNow;
So DatetimeOffset is good for storing the difference or Offset w.r.t UTC.
For more details refer to MSDN.