首页 > 解决方案 > 如何获得两个时区之间的时间差以及夏令时

问题描述

我需要根据用户的个人资料动态获取两个时区之间的差异。

假设如果我是用户 A,今天我的个人资料位于源时区的 MST 时区,而我的目标时区位于 PST 时区,那么我需要获取 MST 和 PST 的小时差。让我们假设 3 小时是差异然后我需要得到这三个小时的差异。

同时另一个用户B可能在源时区的CST时区,而目标时区在HST时区,那么我需要得到CST和HST的小时差。假设1小时是差异然后我需要得到这一小时的差异。

如果“N”个用户正在使用该应用程序并且如果他们处于夏令时,则应根据夏令时进行时区计算,如果他们没有夏令时,则应在不考虑日光的情况下进行时区计算。

我该如何实施?任何人都可以帮助我,因为我是新手。

标签: c#

解决方案


这种机制已经为我工作了多年。Windows 使用一个注册表项来维护本地计算机的时区信息。我不记得版本,但是,几年前.NET 将时区信息包装到 TimeZoneInfo 对象中,在此之前您必须自己编写一个包装器。下面的 psuedo 显示了一般用法。基本租户是:

1. Each client receives the time from the DB or other Layer as UTC. (all datetimes saved as UTC)
2. Using the client profile, convert the UTC DateTime value to the client's local value.
3. Display the date and do date math in the user's local time.
4. Before sending the time to the DB or another layer with different TZ convert back to UTC.

这应该保持您的日期逻辑合理。

string userTimeZone = GetUsersTimeZone();
DateTime timeReadFromDBOrSomewhereInUTC = GetSomeDateTimeInUTC();


DateTime timeInUsersTimeZone = FromUTCToSpecificTimeZone(userTimeZone ,timeReadFromDBOrSomewhereInUTC );

edtTimeForAppointment.Text = timeInUsersTimeZone.ToString();

timeInUsersTimeZone.AddHours(2);

DateTime timeConvertedToUTCToSaveToDB = FromSpecificTimeZoneToUTC(userTimeZone,timeInUsersTimeZone);

下面是使用 TimeZoneInfo 的两个函数的示例。

public static DateTime FromSpecificTimeZoneToUTC(TimeZoneInfo fromZone, DateTime specificTimeZoneDateTime)
{
    DateTime temp = DateTime.SpecifyKind(specificTimeZoneDateTime, DateTimeKind.Unspecified);
    return TimeZoneInfo.ConvertTimeToUtc(temp, fromZone);
}

public static DateTime FromUTCToSpecificTimeZone(TimeZoneInfo toZone, System.DateTime UTCTimeZoneDateTime)
{           
    return TimeZoneInfo.ConvertTimeFromUtc(UTCTimeZoneDateTime, toZone);
}

如果您只需要DateTime两个 timrzones 之间的偏移量,那么下面的函数可能会很有用。

public static TimeSpan GetTimeZoneOffsetDifference(TimeZoneInfo oldZone, TimeZoneInfo newZone)
{           
    var now = DateTimeOffset.UtcNow;
    TimeSpan oldOffset = oldZone.GetUtcOffset(now);
    TimeSpan newOffset = newZone.GetUtcOffset(now);
    TimeSpan difference = oldOffset - newOffset;
    return difference;
}

推荐阅读