【问题标题】:TimeZoneInfo|GetUtcOffset: A better solution?TimeZoneInfo|GetUtcOffset:更好的解决方案?
【发布时间】:2010-10-25 18:40:11
【问题描述】:

我面临一个问题,我的服务器需要 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);            
        }
    }

【问题讨论】:

标签: c# datetime timezone


【解决方案1】:

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

在随意使用时,当 第二个不重要,格林威治 可以考虑平均时间 (GMT) 相当于 UTC 或 UT1。说“格林威治标准时间” 通常意味着 UTC 或 UT1 在非正式或随意使用 上下文。在技​​术环境中,使用 避免使用“GMT”;明确的 术语“UTC”或“UT1”是 首选。

如果是这样,问题就解决了:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-20
    • 2011-11-21
    • 1970-01-01
    • 1970-01-01
    • 2020-02-15
    相关资源
    最近更新 更多