WCF converting time based on timezone automatically

拈花ヽ惹草 提交于 2019-12-22 05:35:28

问题


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?


回答1:


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

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();


来源:https://stackoverflow.com/questions/1356384/wcf-converting-time-based-on-timezone-automatically

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!