c# - 时区信息|GetUtcOffset : A better solution?

标签 c# datetime timezone

我面临一个问题,我的服务器需要 GMT 格式的日期时间对象,而我的 UI 应用程序总是根据本地文化创建和操作所有日期时间对象。我无法更改文化,因为还有其他功能需要日期时间对象根据本地格式。我为此编写了一个转换器,不确定是否有任何现成的 api 允许我这样做。对 timezoneinfo 上的 GetUtcOffset 方法也有点困惑,它是否给出了本地时间和 gmt 时间之间的差异?我试过了msdn 上可用的文档对我来说有点晦涩难懂。你能帮忙吗?另外,我如何通过更改文化和验证输出来对其进行单元测试?

下面的类将日期时间对象转换为包含等效的 GMT 时间,并在从服务器接收时将其转换回来。

注意:我的服务器和 UI 都在 CET 时间运行,但是这些日期时间对象是英国特定的,因此服务器需要它们在 GMT 时间。

public class GmtConverter : IDateConverter
    {
        private readonly TimeZoneInfo timeZoneInfo;

        public GmtConverter()
            : this(TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time"))
        {

        }
        public GmtConverter(TimeZoneInfo timeZoneInfo)
        {
            this.timeZoneInfo = timeZoneInfo;
        }

        public DateTime Convert(DateTime localDate)
        {
            var utcOffset = timeZoneInfo.GetUtcOffset(localDate);

            var unSpecified = localDate + utcOffset;

            return DateTime.SpecifyKind(unSpecified, DateTimeKind.Unspecified);  
        }

        public DateTime ConvertBack(object local)
        {
            var localDate = (DateTime) local;

            var utcOffset = timeZoneInfo.GetUtcOffset(localDate);

            var unSpecified = localDate - utcOffset;

            return DateTime.SpecifyKind(unSpecified, DateTimeKind.Unspecified);            
        }
    }

最佳答案

当你说 GMT 时,你指的是 UTC 吗?来自 Wikipedia :

In casual use, when fractions of a second are not important, Greenwich Mean Time (GMT) can be considered equivalent to UTC or UT1. Saying "GMT" often implies either UTC or UT1 when used within informal or casual contexts. In technical contexts, usage of "GMT" is avoided; the unambiguous terminology "UTC" or "UT1" is preferred.

如果是,则问题解决:

关于c# - 时区信息|GetUtcOffset : A better solution?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4017713/

相关文章:

c# - 如何实现 "masterpage"级别的逻辑

java - 使用 SQL 将 Date Java 与数据库表中的 DateTime 列进行比较

datetime - 将给定时间转换为 Perl 中的站点特定时间

c# - 将最近 2 周的数据拆分为当前周和前一周

c# - 使用左连接的 LINQ orderby FK

java - 仅动态列出特定日期的两个日期之间的日期

java - 在其他时区午夜时获取本地时间

postgresql - 如何将字符串视为 UTC 时间戳?

c# - 如何在我的 Visual Studio 2012 项目中引用 XML 文件作为项目代码中的数据源?

python - 用 pandas 计算每天的值总数