我正面临一个问题,其中我的服务器需要格式为GMT格式的日期时间对象,而且我的UI应用程序始终根据本地文化创建和操作所有日期时间对象。我无法更改文化,因为还有其他需要日期时间对象的功能根据当地的格式。我已经为此写了一个转换器,不确定是否有任何现成的api允许我这样做。还有一点关于timezoneinfo上的GetUtcOffset方法有点困惑,它是否给出了本地时间和gmt时间之间的差异?我试过了在msdn上可用的文档对我来说有点脆弱。请问你能帮忙吗?我该如何单元测试它,通过改变文化和验证输出?TimeZoneInfo | GetUtcOffset:更好的解决方案?
下面的类将日期时间对象转换为包含等效的GMT时间,并在从服务器接收时将其转换回来。
注意:我的服务器和用户界面都在CET时间运行,但这些日期时间对象是英国特定的,因此服务器需要格林威治标准时间。
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);
}
}
相关问题:http://stackoverflow.com/questions/2532729/daylight-saving-time -and-时区 - 最佳实践 – Oded 2010-10-25 18:43:51