C# DateTime to UTC Time without changing the time

C#DatetimeUtc

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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

Solution 3 - C#

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

Solution 4 - C#

Use the DateTime.ToUniversalTime method.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLuke BelbinaView Question on Stackoverflow
Solution 1 - C#tofutimView Answer on Stackoverflow
Solution 2 - C#user166390View Answer on Stackoverflow
Solution 3 - C#InBetweenView Answer on Stackoverflow
Solution 4 - C#FemarefView Answer on Stackoverflow