163

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,708
  • 12
  • 52
  • 75

4 Answers4

270
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
  • 22,664
  • 20
  • 87
  • 148
  • 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 – AlexAlum Sep 17 '21 at 09:42
  • Just stumbled on this. Be aware that if you parse a DateTime from a Iso string "YYYY-MM-ddTHH-mm-ss" that you don't add a "Z" at the end. Otherwise SpecifyKind will change your hours. – garcipat Jul 03 '23 at 14:27
70

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
  • 27,717
  • 28
  • 128
  • 190
32

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
  • 32,319
  • 3
  • 50
  • 90
  • 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
-10

Use the DateTime.ToUniversalTime method.

Femaref
  • 60,705
  • 7
  • 138
  • 176