转换PST到服务器时区的格林尼治标准​​时间无论与.net日期时间格林尼治、时间、时区、日期

2023-09-06 17:59:43 作者:曾经的誓言,只因太年轻

给定结构为一个日期和时间:

Given a date and time structured as:

2011-10-21 14点44分19秒

"2011-10-21 14:44:19"

这是众所周知的是太平洋时间(调整为夏令时在适当的时候),我需要解析的日期时间,并将其转换为UTC,不论的当前的服务器时间。

which is known to be Pacific Time (adjusted for Daylight Savings when appropriate), I need to parse the DateTime and convert it to UTC, irrespective of the current server time.

我已经看到了这一点,在假设原来的日期时间为UTC开始非常类似的问题:

I have seen this very similar question that starts with the assumption that the original DateTime is in UTC:

How不论区域设置格式化日期时间为GMT?

我想它应用到我的情况,但不知道如何开始一个太平洋时间(PST或PDT如适用)串并得出一个UTC日期时间。具体而言,该解决方案适用的标志 DateTimeStyles.AssumeUniversal ,而我需要承担起太平洋时间。

I'm trying to apply that to my situation, but don't understand how to begin with a Pacific Time (PST or PDT as appropriate) string and arrive at a UTC DateTime. Specifically, that solution applies the flag DateTimeStyles.AssumeUniversal, whereas I need to assume Pacific Time.

推荐答案

您将不得不使用TimeZoneInfo.ConvertTimeToUtc(日期时间,的TimeZoneInfo)进行转换。服务器的时区没有关系。使用FindSystemTimeZoneById()来选择你传递的第二个参数的时区。你会想太平洋标准时间为ID。

You are going to have to use TimeZoneInfo.ConvertTimeToUtc(DateTime, TimeZoneInfo) to make the conversion. The server's timezone doesn't matter. Use FindSystemTimeZoneById() to select the timezone you pass as the second argument. You'll want "Pacific Standard Time" for the id.

这个函数使用的存储在注册表中,由Windows维护的时区数据库。时区规则随着时间而改变,尤其是夏令时转换,因此保持Windows更新激活的机器上是很重要的,让微软更新数据库。明知的完全的其中字符串是从哪里来重要的是这个工作正确的。

This function uses a timezone database that's stored in the registry and maintained by Windows. Timezone rules change over time, particularly daylight savings transitions, so keeping Windows Update active on that machine is important to allow Microsoft to update the database. Clearly knowing exactly where the string came from is important for this to work correctly at all.