gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 16:50:57 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com