C#DateTime到UTC时间,而无需更改时间


124

如何在不更改实际时间的情况下将现有的日期时间转换为UTC时间。

例:

DateTime dateTime = GetSomeDateTime(); // dateTime here is 3pm
dateTime.ToUtcDateTime() // datetime should still be 3pm

您在PST吗?您如何获得PST价值?
Kiquenet '18

Answers:


207
6/1/2011 4:08:40 PM Local
6/1/2011 4:08:40 PM Utc

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

50

使用DateTime.SpecifyKind静态方法。

创建一个新的DateTime对象,该对象的跳动次数与指定的DateTime相同,但被指定为本地时间,协调世界时(UTC)或都不指定,如指定的DateTimeKind值所示。

例:

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

18

您可以使用的重载构造函数DateTime

DateTime utcDateTime = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, DateTimeKind.Utc);

0

您也可以通过以下方式进行操作:

DateTime utcDateTime = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second).ToUniversalTime();

这可能无法正常工作。尝试... new DateTime(dateTime.Year, dateTime.Month, dateTime.dateTimeay, dateTime.Hour, dateTime.Minute, dateTime.Second).ToUniversalTime().ToString() vs DateTime.SpecifyKind(dateTime, DateTimeKind.Utc).ToString() 您会看到不同的结果。
荷马

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.