开发者

Difference between System.DateTime and System.DateTimeOffset

开发者 https://www.devze.com 2023-03-16 21:05 出处:网络
Can anyone explain the difference between System.DateTime and System.DateTimeOffset in C#.NET? Which is best suited for building web apps with use开发者_运维百科rs from different time zones?A DateTime

Can anyone explain the difference between System.DateTime and System.DateTimeOffset in C#.NET? Which is best suited for building web apps with use开发者_运维百科rs from different time zones?


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


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:

 DateTime.UtcNow.ToLocalTime();

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:

 myUTCDate.toLocaleTimeString();

http://www.java2s.com/Code/JavaScript/Date-Time/ConvertDatetoLocaleString.htm


DateTimeOffset represents the datetime as UTC datetime.

So

DateTimeOffset dtoNow = DateTimeOffset.Now;

is same as

DateTimeOffset dtoUTCNow = DateTimeOffset.UTCNow;

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消