Zoltan Hernyak
Zoltan Hernyak

Reputation: 1239

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);

Upvotes: 1

Views: 1590

Answers (2)

Tomse
Tomse

Reputation: 189

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. 

Results: The current DateTime object is assumed to be local time, and the conversion is performed as if Kind were Local.

The default is Unspecified.

The ToUniversalTime method converts a DateTime value from local time to UTC. To convert the time in a non-local time zone to UTC, use the TimeZoneInfo.ConvertTimeToUtc(DateTime, TimeZoneInfo) method. To convert a time whose offset from UTC is known, use the ToUniversalTime method.

Upvotes: 6

Synapsis
Synapsis

Reputation: 1017

The method ToUniversalTime converts a DateTime value of the local hour to a UTC hour. If you want to convert a time value wich UTC value is known you can use this method

Upvotes: 0

Related Questions