繁体   English   中英

如何获得两个时区之间的时差以及夏令时

[英]how to get the difference of time between two timezones along with day light saving

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

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

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

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

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

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

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);
}

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

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;
}

我们过去曾使用解析过的DateTimeOffset处理过这个问题

  • JavaScript 在表单提交期间插入用户的本地时间
  • 我们在其中以分钟为单位保存首选时区偏移的用户配置文件

我们将偏移量存储为SMALLINT而不是替代方案,因为使用TimeSpan.FromMinutes非常容易,因此我们可以支持时区而不仅仅是一个小时的偏移量(例如印度是 UTC+5:30)。

通过将 DateTimeOffset 存储在具有准确 UTC 偏移量的数据库中,我们已经能够根据自己的喜好进行报告(通过 UTC 或转换为首选时区)或显示满足我们要求的审计/数据表。

话虽如此,我想有更好的和许多其他方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM