Adding Seconds to DateTime with a Valid Double Results in ArgumentOutOfRangeException

前端 未结 7 1230

The following code crashes and burns and I don\'t understand why:

DateTime dt = new DateTime(1970,1,1,0,0,0,0, DateTimeKind.Utc);
double d = double.Parse(\"1         


        
相关标签:
7条回答
  • 2021-01-17 11:00

    I had a similar issue where I was required to add a configurable timespan to a datetime. If the configuration is not correct I have to assume the 'worst scenario' : MaxValue.

    I solved it by implementing an extension to DateTime (still in test phase) :

        /// <summary>
        /// Removes a timespan from a date, returning MinValue or MaxValue instead of throwing exception when if the resulting date
        /// is behind the Min/Max values
        /// </summary>
        /// <returns></returns>
        public static DateTime SafeAdd(this DateTime source, TimeSpan value)
        {
            // Add or remove ?
            if (value.Ticks > 0)
            {
                // add
                var maxTicksToAdd = DateTime.MaxValue - source;
                if (value.Ticks > maxTicksToAdd.Ticks)
                    return DateTime.MaxValue;
            }
            else
            {
                var maxTicksToRemove = source - DateTime.MinValue;
    
                // get the value to remove in unsigned representation.
                // negating MinValues is impossible because it would result in a value bigger than MaxValue : (-32768 .. 0 .. 32767)
                var absValue = value == TimeSpan.MinValue ? TimeSpan.MaxValue : -value;
    
                if (absValue.Ticks > maxTicksToRemove.Ticks)
                    return DateTime.MinValue;
            }
            return source + value;
        }
    
    0 讨论(0)
提交回复
热议问题