C# DateTime to UTC Time without changing the time
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
Solution 1:
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:
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