【发布时间】: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);
}
}
【问题讨论】: