首页 > 解决方案 > What does .ToUniversalTime() really do on a DateTime instance (C#)?

问题描述

What is the real difference between the following d,e,f values? What the 'ToUniversalTime()' really do?

  var d = DateTime.Now;
  var e = d.ToUniversalTime();
  var f = e;

Does somebody knows? Thanks.

Remark: we detected differences on an EF query, when the 'Created' field is a datetime sql field, and contains UTC time:

var itemsD = ctx.Log.Where(p => p.Created > d);
var itemsE = ctx.Log.Where(p => p.Created > e);

标签: c#datetimeutc

解决方案


The value returned by the "ToUniversalTime" method is determined by the "Kind" property of the current DateTime object. The following describes the possible results:

Kind: Utc 

Results: No conversion is performed.

Kind: Local. 

Results: The current DateTime object is converted to UTC.

Kind: Unspecified. 

结果:当前的 DateTime 对象被假定为本地时间,并且按照 Kind 是 Local 的方式执行转换。

默认为未指定。

ToUniversalTime 方法将 DateTime 值从本地时间转换为 UTC。要将非本地时区的时间转换为 UTC,请使用 TimeZoneInfo.ConvertTimeToUtc(DateTime, TimeZoneInfo) 方法。要转换与 UTC 的偏移量已知的时间,请使用 ToUniversalTime 方法。


推荐阅读