C# DateTime to UTC Time without changing the time

前端 未结 4 1532
渐次进展
渐次进展 2020-12-25 09:33

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

Example:

DateTime dateTime = GetSomeDateTime(); // dateTime          


        
4条回答
  •  生来不讨喜
    2020-12-25 09:42

    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
    

提交回复
热议问题