时区分钟偏移量的 TimeZoneInfo

TimeZoneInfo from timezone minutes offset(时区分钟偏移量的 TimeZoneInfo)

本文介绍了时区分钟偏移量的 TimeZoneInfo的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从 JavaScript 中,我使用 Date 对象上的方法 getTimezoneOffset 将用户客户端日期时间与 UTC 偏移的分钟数传递给控制器​​.现在我在服务器端有了这些信息,我想从中创建一个 TimeZoneInfo.这怎么可能?如果这是不可能的,那么如何使用分钟偏移量将服务器端的 UTC 日期转换为客户端的时区?

From JavaScript I have passed, to the controller, the number of minutes that the user's client date time is offset from UTC using the method getTimezoneOffset on the Date object. Now that I have this information on the server side I'd like to create a TimeZoneInfo from it. How is this possible? If this is not possible then how can I convert UTC dates on the server side into the client's timezone using the minutes offset?

推荐答案

我想从中创建一个 TimeZoneInfo.这怎么可能?

I'd like to create a TimeZoneInfo from it. How is this possible?

这是不可能的.时区偏移时区不同.请阅读时区标签wiki,尤其是标题为时区!=偏移"的部分.

It's not possible. A time zone offset is not the same thing as a time zone. Please read the timezone tag wiki, especially the section titled "Time Zone != Offset".

...那么如何使用分钟偏移量将服务器端的 UTC 日期转换为客户端的时区?

... then how can I convert UTC dates on the server side into the client's timezone using the minutes offset?

创建一个代表那个时刻的 DateTimeOffset.例如:

Create a DateTimeOffset that represents that moment in time. For example:

// 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 中从客户端检索到的偏移量不一定是适用于数据库日期的正确偏移量.当您获得偏移量时,它必须是针对特定时间的.由于许多时区会更改夏令时的偏移量,您不能假设您当前拥有的偏移量适用于数据库中的任何特定值.因此,虽然上面的代码可以满足您的要求,但总的来说它可能仍然不是一个好主意.

Also, make sure you understand that the offset you retrieved from the client in JavaScript is not necessarily the correct offset to apply to your database date. When you get the offset, it has to be for a particular moment in time. Since many time zones change offsets for daylight saving time, you cannot assume that the offset you currently have is appropriate for any particular value in your database. Therefore, while the above code does what you asked, it is probably still not a good idea in general.

这篇关于时区分钟偏移量的 TimeZoneInfo的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:时区分钟偏移量的 TimeZoneInfo

基础教程推荐