WCF根据时区自动转换时间 [英] WCF converting time based on timezone automatically

查看:21
本文介绍了WCF根据时区自动转换时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 WCF 服务,它返回服务器的当前时间.我的客户在不同的时区.当我调用此服务时,它会自动将服务器返回的时间转换为本地时间,这是我不想要的.我如何忽略这个?

I am using WCF service which returns current time of the server. My Client is in different time zone. When I call this service, It is automatically converting the time returned by the server to local time, which I do not want. How do i ignore this?

推荐答案

将从 WCF 服务发出的转换为 UTC,并在客户端中创建新时间时,将它们指定为 UTC 类型.这将使时间基线为通用标准时区.您可以向客户显示时间,并确保将其标识为 UTC 时间.这将减少关于那个时间究竟是什么的任何差异或歧义.

Convert your sent out from the WCF service to UTC, and when you create new times in your client, specify them as kind UTC. This will baseline the time to the universal standard time zone. You could display the time to your client and make sure to identify it as UTC time. That will alleviate any discrepancy or ambiguity about what that time really is.

DateTime serverTimeRaw = myService.GetServerTime();
DateTime serverTimeUTC = new DateTime(serverTimeRaw.Ticks, DateTimeKind.Utc);
Console.WriteLine(serverTimeUTC); // Prints server time as UTC time

如果您确实需要在相应的时区中表示时间,则需要将时区信息与 DateTime 一起发送.我建议创建一个封装这两条信息的类型,并返回它,而不是 DateTime 本身.时区信息不是 DateTime 的固有组件.这是两个独立的关注点,只有在实际组合时才提供复合含义.

If you actually need to represent times in their appropriate time zone, you will need to send the time zone information along with the DateTime. I would recommend creating a type that encapsulates both pieces of information, and return that, rather than a DateTime itself. Time zone information is not an intrinsic component of a DateTime. Those are two separate concerns, and only provide composite meaning when actually composed.

class ZonedDateTime
{
    public DateTime DateTimeUtc { get; set; }
    public TimeZoneInfo TimeZone { get; set; }

    public DateTime ToDateTime()
    {
        DateTime dt = TimeZoneInfo.ConvertTime(DateTimeUtc, TimeZone);
        return dt;
    }
}

// ...

ZonedDateTime zdt = myService.GetServerZonedTime();
DateTime serverTimeActual = zdt.ToDateTime();

这篇关于WCF根据时区自动转换时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆