开发者

Is this a correct use of DateTime? Will it work for all timezones?

So, I'm storing a DateTime object as a private member on an object. This private member is set on object creation like so:

this.mCreateDate = DateTime.UtcNow.ToUniversalTime();

Now, later on in the application, I want to see how long the object has been alive for. This could be many weeks (this is a long ru开发者_如何学运维nning web app).

I'm getting the object lifetime like so:

DateTime now = DateTime.UtcNow.ToUniversalTime();

TimeSpan objectLifetime = now.Subtract(Foo.CreateDate);

// Output formatted time span

Does this all look correct?


First, calling ToUniversalTime() on DateTime.UtcNow is redundant, since .net 2.0, no conversion happens if the "Kind" of the source DateTime object is "Utc".

Other than that, this looks fine.


This seems correct, and you're following the golden rule of DateTime: Use UTC, display in local!


Your approach seems correct to me although I think it is more appropriate to use the DateTimeOffset structure, which is new since .NET 3.5.

I quote Anthony Moore:

  • Use DateTimeOffset whenever you are referring to an exact point in time. For example, use it to calculate "now", transaction times, file change times, logging event times, etc. If the time zone is not known, use it with UTC. These uses are much more common than the scenarios where DateTime is preferred, so this should be considered the default.
  • Use DateTime for any cases where the absolute point in time does not apply: e.g. store opening times that apply across time zones.
  • Use DateTime for interop scenarios where the information is a Date and Time without information about the time zone, e.g. OLE Automation, databases, existing .NET APIs that use DateTime, etc.
  • Use DateTime with a 00:00:00 time component to represent whole dates, e.g. Date of irth.
  • Use TimeSpan to represent times of day without a date.

So you could simply write:

this.mCreateDate = DateTimeOffset.Now;
//...
TimeSpan lifeTime = DateTimeOffset.Now - Foo.CreateDate;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜