我正在尝试创建一个将时间从一个时区转换到另一个时区的小方法。我认为这会很简单,但当我部署它时,我得到这个错误The UTC Offset of the local dateTime parameter does not match the offset argument.
我的猜测是,这是因为服务器和用户不在同一时区,这是没有帮助的,因为这将从世界各地使用。
public object ConvertDate(DateTime inputTime, string fromOffset, string toZone)
{
var fromTimeOffset = new TimeSpan(0, - int.Parse(fromOffset), 0);
var to = TimeZoneInfo.FindSystemTimeZoneById(toZone);
var offset = new DateTimeOffset(inputTime, fromTimeOffset);
var destination = TimeZoneInfo.ConvertTime(offset, to);
return destination.DateTime;
}
其中fromOffset
是一个数字,从用户时区转换为timespan,toZone
是我们要转换到的区域的名称。错误发生在此行var offset = new DateTimeOffset(inputTime, fromTimeOffset);
上
你有什么办法让它工作起来吗?
发布于 2018-01-30 06:41:45
下面是我用来绕过这个令人难以置信的令人沮丧的框架决策的扩展方法。请参阅注释,处理这个问题的最好和最有效的方法是使用DateTimeOffset
的ticks构造函数,而不是仅仅为了更改它的Kind
属性而必须分配另一个中间DateTime
。
/// <summary>
/// Converts a DateTime to a DateTimeOffset, without risking any onerous exceptions
/// the framework quite unfortunately throws within the DateTimeOffset constructor,
/// such as they do when the source DateTime's Kind is not set to UTC. The best and
/// most performant way around this, which we do herein, is to simply construct the
/// new DateTimeOffset with the overload that excepts Ticks. Also, we will simply
/// return <see cref="DateTimeOffset.MinValue"/> if the source DateTime was
/// <see cref="DateTime.MinValue"/>.
/// </summary>
/// <param name="dt">Source DateTime.</param>
/// <param name="offset">Offset</param>
public static DateTimeOffset ToDateTimeOffset(this DateTime dt, TimeSpan offset)
{
// adding negative offset to a min-datetime will throw, this is a
// sufficient catch. Note however that a DateTime of just a few hours can still throw
if (dt == DateTime.MinValue)
return DateTimeOffset.MinValue;
return new DateTimeOffset(dt.Ticks, offset);
}
public static DateTimeOffset ToDateTimeOffset(this DateTime dt, double offsetInHours = 0)
=> ToDateTimeOffset(dt, offsetInHours == 0 ? TimeSpan.Zero : TimeSpan.FromHours(offsetInHours));
https://stackoverflow.com/questions/36255821
复制相似问题