C# DateTime to UTC Time without changing the time

前端 未结 4 1533
渐次进展
渐次进展 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
    
    0 讨论(0)
  • 2020-12-25 09:43
    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);
    
    0 讨论(0)
  • 2020-12-25 09:46

    Use the DateTime.ToUniversalTime method.

    0 讨论(0)
  • 2020-12-25 09:50

    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);
    
    0 讨论(0)
提交回复
热议问题