我从 JavaScript 向 Controller 传递了用户客户端日期时间与 UTC 之间的偏移分钟数,使用 Date
对象上的 getTimezoneOffset
方法。现在我在服务器端有了这些信息,我想从中创建一个 TimeZoneInfo。这怎么可能?如果这不可能,那么我如何使用分钟偏移量将服务器端的 UTC 日期转换为客户端的时区?
最佳答案
I'd like to create a TimeZoneInfo from it. How is this possible?
这是不可能的。 时区偏移量与时区不同。请阅读timezone tag wiki ,尤其是标题为“Time Zone != Offset”的部分。
... then how can I convert UTC dates on the server side into the client's timezone using the minutes offset?
创建一个代表那个时刻的 DateTimeOffset
。例如:
// From your database. Make sure you specify the UTC kind.
DateTime utc = new DateTime(2013, 1, 1, 0, 0, 0, DateTimeKind.Utc);
// From JavaScript
int offsetMinutes = 420;
// Don't forget to invert the sign here
TimeSpan offset = TimeSpan.FromMinutes(-offsetMinutes);
// The final result
DateTimeOffset dto = new DateTimeOffset(utc).ToOffset(offset);
此外,请确保您了解您在 JavaScript 中从客户端检索到的偏移量不一定是适用于您的数据库日期的正确偏移量。当您获得偏移量时,它必须是针对特定时刻的。由于许多时区会更改夏令时的偏移量,因此您不能假设您当前拥有的偏移量适用于数据库中的任何特定值。因此,虽然上面的代码完成了您的要求,但总的来说它可能仍然不是一个好主意。
关于c# - 来自时区分钟偏移量的 TimeZoneInfo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18985578/