转换DateTime.Now到不同的时区 [英] Converting DateTime.Now To A Different Time Zone

查看:375
本文介绍了转换DateTime.Now到不同的时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该代码已经工作很长时间了,但现在已经打破,当我试图通过DateTime.Now为outageEndDate参数:

This code has been working for a long time now but has broken now when I try to pass DateTime.Now as the outageEndDate parameter:

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



我就上线得到该错误消息是,Kind属性设置不正确的日期时间参数(outageEndDate)。我GOOGLE和SO检查的例子,但我真的不明白的错误消息。

The error message I am getting on the last line is that the Kind property is not set correctly on the DateTime parameter (outageEndDate). I've Googled and checked SO for examples but I don't really understand the error message.

任何建议表示赞赏。

问候

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

EDIT - The exact error message is:

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



编辑:outageEndDate.Kind = UTC

outageEndDate.Kind = Utc

推荐答案

感谢澄清你的问题。

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

If the DateTime instance Kind is Local, then TimeZoneInfo.ConvertTime will expect the second parameter to be the local timezone of your computer.

如果DateTime的实例 UTC ,然后 TimeZoneInfo.ConvertTime 会期望是UTC时区的第二个参数。

If DateTime instance Kind is Utc, then TimeZoneInfo.ConvertTime will expect the second parameter to be the Utc timezone.

您需要outageEndDate转换为正确的时区第一,以防万一localProvice时区不匹配您的计算机上的时区。

You need to convert outageEndDate to the right timezone first, just in case the localProvice timezone doesn't match the timezone on your computer.

outageEndDate = TimeZoneInfo.ConvertTime(outageEndDate, localTime);

这篇关于转换DateTime.Now到不同的时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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