首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >DateTimeOffset错误:本地dateTime的UTC偏移量与偏移量参数不匹配

DateTimeOffset错误:本地dateTime的UTC偏移量与偏移量参数不匹配
EN

Stack Overflow用户
提问于 2016-03-28 12:06:41
回答 1查看 16.2K关注 0票数 29

我正在尝试创建一个将时间从一个时区转换到另一个时区的小方法。我认为这会很简单,但当我部署它时,我得到这个错误The UTC Offset of the local dateTime parameter does not match the offset argument.我的猜测是,这是因为服务器和用户不在同一时区,这是没有帮助的,因为这将从世界各地使用。

代码语言:javascript
复制
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);

你有什么办法让它工作起来吗?

EN

回答 1

Stack Overflow用户

发布于 2018-01-30 06:41:45

下面是我用来绕过这个令人难以置信的令人沮丧的框架决策的扩展方法。请参阅注释,处理这个问题的最好和最有效的方法是使用DateTimeOffset的ticks构造函数,而不是仅仅为了更改它的Kind属性而必须分配另一个中间DateTime

代码语言:javascript
复制
    /// <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));
票数 13
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36255821

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档