当种类为Utc时,将UTC中的DateTime转换为DateTimeOffset 时出错。 origDateTime来自webservice,所以我不能控制内容或格式。 在大多数情况下它与Kind = Unspecified(即使艰难的时间在Utc),然后它的工作,但在极少数情况下Kind = Utc,然后转换为DateTimeOffset引发异常: “UTC抵消Utc DateTime实例必须为0. \ r \ n参数名称:偏移量“ 我应该如何解决它?当种类为Utc时,从datetime UTC转换为datetimeoffset时出错
try {
//cause error !!!!
DateTime databaseUtcTime = DateTime.Parse("4/2/2016 6:25:20 PM");
var localTimeTemp = databaseUtcTime.ToLocalTime();
DateTime origDateTime = localTimeTemp.ToUniversalTime();
//this is working
//DateTime origDateTime = DateTime.Parse("4/2/2016 6:25:20 PM");
string timeZoneName = "Pacific Standard Time";
TimeZoneInfo localTimeZone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneName);
DateTimeOffset localTime = new DateTimeOffset(origDateTime, localTimeZone.GetUtcOffset(origDateTime));
return localTime;
}
catch (Exception ex) {
string msg = ex.Message;
return null;
}
DATATIME解析使用时区设置,所以无需转换自动转换为UTC时间。与数据库的连接也自动使用UTC时间,所以你的代码没有多大意义。输入在另一时区收集的数据时或在另一时区显示时间时,仅使用时区偏移。网络库函数将时间存储在计算机中,以UTC的数字表示,并在输入或输出时自动转换UTC。 – jdweng
我需要使用不同的时区(根据另一个字段)将每个日期时间转换为datetimeoffset,以便能够显示在不同的时区中。泽维尔回答解决了这个问题。谢谢。 – user2455595