146

How would I convert a preexisting datetime to UTC time without changing the actual time.

Example:

DateTime dateTime = GetSomeDateTime(); // dateTime here is 3pm
dateTime.ToUtcDateTime() // datetime should still be 3pm
Luke Belbina
  • 5,434
  • 11
  • 49
  • 72

4 Answers4

247
6/1/2011 4:08:40 PM Local
6/1/2011 4:08:40 PM Utc

from

DateTime dt = DateTime.Now;            
Console.WriteLine("{0} {1}", dt, dt.Kind);
DateTime ut = DateTime.SpecifyKind(dt, DateTimeKind.Utc);
Console.WriteLine("{0} {1}", ut, ut.Kind);
tofutim
  • 21,324
  • 20
  • 81
  • 144
  • Considering net framework 4.8 and older there's a bug with time zones. Net 5.0 (which is the latest version for the time I post this comment) is OK. See here my answer https://stackoverflow.com/a/69221062/6435004 – Aluminium Sep 17 '21 at 09:42
62

Use the DateTime.SpecifyKind static method.

Creates a new DateTime object that has the same number of ticks as the specified DateTime, but is designated as either local time, Coordinated Universal Time (UTC), or neither, as indicated by the specified DateTimeKind value.

Example:

DateTime dateTime = DateTime.Now;
DateTime other = DateTime.SpecifyKind(dateTime, DateTimeKind.Utc);

Console.WriteLine(dateTime + " " + dateTime.Kind); // 6/1/2011 4:14:54 PM Local
Console.WriteLine(other + " " + other.Kind);       // 6/1/2011 4:14:54 PM Utc
Liam
  • 25,247
  • 27
  • 110
  • 174
26

You can use the overloaded constructor of DateTime:

DateTime utcDateTime = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, DateTimeKind.Utc);
InBetween
  • 31,483
  • 3
  • 49
  • 86
  • The solution is a bit awkward for the OP's question, but worked well for me for creating a new brand new `DateTime`. – ahong Jan 03 '21 at 07:25
-9

Use the DateTime.ToUniversalTime method.

Femaref
  • 59,667
  • 7
  • 131
  • 173