我在转换服务器和客户端之间的日期时遇到了一个问题,这两个服务器和客户端都在德国运行。客户端机器上的区域设置可以设置为英国或德国。我从服务器收到一个CET格式的日期,我需要将这个时间在UI上表示为英国时间。例如,从服务器接收的时间,例如01/07/2010 01:00:00,应该在ui上表示为01/07/2010 00:00:00。我已经为这个目的写了一个转换器,但是在运行它的时候得到了2个小时的时间差。下面是代码,你能帮忙吗?

public class LocalToGmtConverter : IDateConverter
{
    private readonly TimeZoneInfo timeZoneInfo;

    public LocalToGmtConverter()
        : this(TimeZoneInfo.Local)
    {

    }
    public LocalToGmtConverter(TimeZoneInfo timeZoneInfo)
    {
        this.timeZoneInfo = timeZoneInfo;
    }

    public DateTime Convert(DateTime localDate)
    {
        var utcKind = DateTime.SpecifyKind(localDate, DateTimeKind.Utc);
        return utcKind;
    }

    public DateTime ConvertBack(object fromServer)
    {
        DateTime serverDate = (DateTime)fromServer;

        var utcOffset = timeZoneInfo.GetUtcOffset(serverDate);

        var uiTime = serverDate- utcOffset;

        return uiTime;

    }
}

最佳答案

我认为你正在转换到UTC(而不是英国)时间。由于中欧地区仍有夏季(如果气温不这么说的话,也算是夏季),所以在10月31日之前,两者的时差是+2小时。
如果你知道你要从德国转为英国(也就是说,夏季CEST转为英国夏令时,冬季CET转为GMT),为什么不干脆减1小时呢?
如果您想要英国的时区信息,可以使用

var britishZone = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");

然后可以使用
var newDate = TimeZoneInfo.ConvertTime(serverDate, TimeZoneInfo.Local, britishZone);

07-28 02:20