将DateTime.Now转换为不同的时区

Kev*_*vin 4 c# datetime

这段代码已经工作了很长时间,但是当我尝试将DateTime.Now作为outageEndDate参数传递时,它已经破了:

public Outage(DateTime outageStartDate, DateTime outageEndDate, Dictionary<string, string> weeklyHours, string province, string localProvince)
    {
        this.outageStartDate = outageStartDate;
        this.outageEndDate = outageEndDate;
        this.weeklyHours = weeklyHours;
        this.province = province;
        localTime = TimeZoneInfo.FindSystemTimeZoneById(timeZones[localProvince]);

        if (outageStartDate < outageEndDate)
        {
            TimeZoneInfo remoteTime = TimeZoneInfo.FindSystemTimeZoneById(timeZones[province]);
            outageStartDate = TimeZoneInfo.ConvertTime(outageStartDate, localTime, remoteTime);
            outageEndDate = TimeZoneInfo.ConvertTime(outageEndDate, localTime, remoteTime);
Run Code Online (Sandbox Code Playgroud)

我在最后一行得到的错误消息是在DateTime参数(outageEndDate)上没有正确设置Kind属性.我用谷歌搜索并检查了SO的例子,但我真的不明白错误信息.

任何建议表示赞赏.

问候.

编辑 - 确切的错误消息是:

The conversion could not be completed because the supplied DateTime did not have the Kind
property set correctly.  For example, when the Kind property is DateTimeKind.Local, the source
time zone must be TimeZoneInfo.Local.  Parameter name: sourceTimeZone
Run Code Online (Sandbox Code Playgroud)

编辑:outageEndDate.Kind = Utc

Mon*_*mas 8

谢谢你澄清了你的问题.

如果DateTime实例KindLocal,那么TimeZoneInfo.ConvertTime将期望的第二个参数是你的计算机的本地时区.

如果DateTime实例KindUtc,那么TimeZoneInfo.ConvertTime将期望第二个参数是Utc时区.

您需要先将outageEndDate转换为正确的时区,以防localAdvice时区与您计算机上的时区不匹配.

outageEndDate = TimeZoneInfo.ConvertTime(outageEndDate, localTime);
Run Code Online (Sandbox Code Playgroud)