有没有一种方法可以在本地时区以外的时区实例化datetime对象?

本文关键字:时区 实例化 对象 datetime 一种 方法 有没有 | 更新日期: 2023-09-27 18:18:50

我整个下午都在绞尽脑汁想弄明白这个问题。从本质上讲,问题本身似乎很简单。我得到一个代表另一个时区(不是本地)的日期和时间的日期/时间。我想将此值转换为UTC值以存储在数据库中。然而,我在网上找到的所有方法似乎都指向您从UTC开始或从本地时区开始。您可以从这些时区转换到其他时区,但您不能从其他时区开始。因此,看起来我必须做一些复杂的偏移计算来做我想做的事情。下面是这个问题的一个例子:

var dateString = "8/20/2014 6:00:00 AM";
DateTime date1 = DateTime.Parse(dateString, 
                      System.Globalization.CultureInfo.InvariantCulture);
var currentTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
// Now the server is set to Central Standard Time, so any automated offset calculation that it runs will come from that point of view:
var utcDate = date1.ToUniversalTime; // This is wrong
// Similarly, if I try to reverse-calculate it, it doesn't work either
var convertedDate = TimeZoneInfo.ConvertTime(date1, currentTimeZone);
utcDate = convertedDate.ToUniversalTime; // This is also wrong
实际上,我想以某种方式告诉系统,我当前处理的datetime对象是来自该时区而不是本地时区的,这样我就知道转换是正确的。我知道我最终需要在那里计算日光节约时间,但这是另一天的问题。

有没有一种方法可以在本地时区以外的时区实例化datetime对象?

这个方法对你有用吗?

TimeZoneInfo。方法从一个时区转换时间到另一个地方。

或者,您可以使用ConvertTimeToUtc方法简单地将任何日期(指定源时区)转换为UTC。

var dateString = "8/20/2014 6:00:00 AM";
DateTime date1 = DateTime.Parse(dateString, 
                      System.Globalization.CultureInfo.InvariantCulture);
var currentTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
var utcDate = TimeZoneInfo.ConvertTimeToUtc(date1, currentTimeZone);

System.DateTime结构体只有两位用于存储"kind"信息。这就是为什么您只能使用"local"或"universal"或"unknown"(或"magic local")。

看一下System.DateTimeOffset结构体。它类似于DateTime,但它也保持时区(从(正负)UTC偏移)。