none
Datetime.Now is throwing a System.ArgumentOutOfRangeException RRS feed

  • Question

  • Hi,

        We have recently migrated our solution from Framework 3.5 to 4.5. After this change, we have detected that the application throws an unexpected exception. The StackTrace is the following:

    Ocurrió System.ArgumentOutOfRangeException
      HResult=-2146233086
      Message=El valor que desea agregar está fuera del intervalo.
    Nombre del parámetro: value
      Source=mscorlib
      ParamName=value
      StackTrace:
           en System.DateTime.Add(Double value, Int32 scale)
           en System.TimeZoneInfo.TransitionTimeToDateTime(Int32 year, TransitionTime transitionTime)
           en System.TimeZoneInfo.GetDaylightTime(Int32 year, AdjustmentRule rule)
           en System.TimeZoneInfo.GetIsDaylightSavingsFromUtc(DateTime time, Int32 Year, TimeSpan utc, AdjustmentRule rule, Boolean& isAmbiguousLocalDst)
           en System.TimeZoneInfo.GetDateTimeNowUtcOffsetFromUtc(DateTime time, Boolean& isAmbiguousLocalDst)
           en System.DateTime.get_Now()
           en C1.Framework.ax.b(Object A_0, MouseEventArgs A_1)
           en System.Windows.Forms.Control.OnMouseMove(MouseEventArgs e)
           en C1.Framework.XView.OnMouseMove(MouseEventArgs e)
           en System.Windows.Forms.Control.WmMouseMove(Message& m)
           en System.Windows.Forms.Control.WndProc(Message& m)
           en C1.Framework.ScrollableControl.WndProc(Message& m)
           en C1.Win.C1Ribbon.C1Ribbon.WndProc(Message& m)
           en System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
           en System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
           en System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
           en System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
           en System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
           en System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
           en System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
           en System.Windows.Forms.Application.Run(Form mainForm)
           en AcquisitionUT.Program.Main() en 


       We use ComponentOne, and, since it appears in the stacktrace, we have checked with several versions. Unfortunately, the problem still persists. The matter is that the exception always occurs when it tries to call to DateTime.Now. We have checked out this link with related problems:

    http://stackoverflow.com/questions/10323881/datetime-now-is-throwing-an-exception

    Does anybody know what could be happening?

      Best regards and thanks in advance.



    • Edited by huanlui Tuesday, December 16, 2014 8:03 AM
    Tuesday, December 16, 2014 8:01 AM

Answers

  • Hello again:

    Following your advice, we have debugged mscorlib code and we have realised that the key could be in the following method of TimeZoneInfo:

           // DateTime.Now fast path that avoids allocating an historically accurate TimeZoneInfo.Local and just creates a 1-year (current year) accurate time zone
            static internal TimeSpan GetDateTimeNowUtcOffsetFromUtc(DateTime timeout Boolean isAmbiguousLocalDst) {
                Boolean isDaylightSavings = false;
    #if FEATURE_WIN32_REGISTRY
                isAmbiguousLocalDst = false;
                TimeSpan baseOffset;
                int timeYear = time.Year;
     
                OffsetAndRule match = s_cachedData.GetOneYearLocalFromUtc(timeYear);
                baseOffset = match.offset;
     
                if (match.rule != null) {
                    isDaylightSavings = GetIsDaylightSavingsFromUtc(time, timeYear, match.offset, match.rule, out isAmbiguousLocalDst);
                    baseOffset += (isDaylightSavings ? match.rule.DaylightDelta : TimeSpan.Zero /* */);                
                }                
                return baseOffset;          
    #else
                // Use the standard code path for the Macintosh since there isn't a faster way of handling current-year-only time zones
                return GetUtcOffsetFromUtc(timeTimeZoneInfo.Localout isDaylightSavingsout isAmbiguousLocalDst);
    #endif // FEATURE_WIN32_REGISTRY
            }


    The program enters in  "if (match.rule != null)" and it ends up throwing an exception at (see CallStack from my first question):

    // Returns the DateTime resulting from adding a fractional number of
        // time units to this DateTime.
        private DateTime Add(double valueint scale) {
            long millis = (long)(value * scale + (value >= 0? 0.5-0.5));
            if (millis <= -MaxMillis || millis >= MaxMillis) 
                throw new ArgumentOutOfRangeException("value"Environment.GetResourceString("ArgumentOutOfRange_AddValue"));
            return AddTicks(millis * TicksPerMillisecond);
        }

      In addition, we have tried turning off "automatically adjust clock for Daylight Saving Time", according the last suggestion of this link:

    http://forum.fs-net.de/index.php/Thread/2887-ArgumentOutOfRangeExcetion-DateTime-Now/

    When turning off AutoDST, the program does not enter in  "if (match.rule != null)" and we work around the problem. The matter is that we have to supply this software to several clients and maybe this solution is not the best for them :).  

    Nevertheless, maybe it could be a clue to find a better solution.

    Thank you all for your support. 


      


    • Edited by huanlui Thursday, December 18, 2014 10:21 AM
    • Marked as answer by Fred BaoModerator Monday, December 29, 2014 8:55 AM
    Thursday, December 18, 2014 10:01 AM

All replies

  • Hello huanlui,

    Here are some links might be helpful, please check them:

    http://stackoverflow.com/questions/6925322/vs-2010-error-value-to-add-was-out-of-range-parameter-name-value

    The shows that your computer setting would cause this error, please check if you are under this scenario and you could try to run your application with a new computer.

    https://social.msdn.microsoft.com/Forums/vstudio/en-US/4c58432d-01ec-4dfb-b4bd-2182f802dfc7/conversion-failed-when-converting-datetime-from-string-or-out-of-range-vbnet?forum=vbgeneral

    This one shows a type conversion resulted in an out-of-range value.

    If above are not helpful, since the .NET is open-sourced, and you could debug into the .NET source yourself according to this blog:

    http://blogs.msdn.com/b/dotnet/archive/2014/02/24/a-new-look-for-net-reference-source.aspx

    I suggest you could try it.

    Regards.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Wednesday, December 17, 2014 2:58 AM
    Moderator
  • Try set your Thread.CurrentThread.CurrentCulture with a new CultureInfo with name = Thread.CurrentThread.CurrentCulture.Name and useUserOverride set to true, then replace DateTimeFormat.Calendar with GregorianCalendar and see if it fixes your issue. I don't use ComponentOne and don't know your regional setting so can't tell if it works or not. If it works you make want to tweak other DateTimeFormatInfo settings to match your need.

    Alternatively if no other things work, try replace your Thread.CurrentThread.CurrentCulture with CultureInfo.InvariantCulture.

    If you can file support request to them, try tell them to swtich their code so all DateTime.Now that is just used to track timespan should be changed to DateTime.UtcNow instead.
    Wednesday, December 17, 2014 7:19 AM
    Answerer
  • Make sure all your executables got recompiled.  I normally recommend making a backup of the bin folder in the project and then deleting the bin folder.  Then recompile.  The dependencies in the compiler doesn't recognize properly when the version of the Net Library changes which often causes exceptions. 

    jdweng

    Wednesday, December 17, 2014 7:33 AM
  • Emmm... Since my suggestion works on Thread level, and the bug occurs in WndProc, I think for most STAThread application it would be good enough to set it on Program.cs, before the main form is loaded, or on the constructor of the form if you want to limit the change (where you'll want to make the form Modal, and remember to restore the original CultureInfo object when the form unloads). And then it should change the behaviors of all assemblies that don't spawn new threads it loads (This include all WinForm UI component libraries).


    Thursday, December 18, 2014 2:20 AM
    Answerer
  • Maybe there is a time difference between two .NET versions, please try to use

    DateTime.Now.AddDays(-1);

    DateTime.Now.AddHours(-1);

    DateTime.Now.AddMinutes(-1);

    DateTime.Now.AddSeconds(-1);

    Please try above and inform if it helps

    Thursday, December 18, 2014 4:41 AM
  • By using the method in your reply, exception should be thrown on DateTime.Now already (i.e.: no chance for the .AddDays() etc. to be run)

    If DateTime.Now don't throw exception, he would have no problem in the beginning.

    And how to add ".AddDays()" to internal code of a third party component without source code is beyond me.


    Thursday, December 18, 2014 6:24 AM
    Answerer
  • Hello again:

    Following your advice, we have debugged mscorlib code and we have realised that the key could be in the following method of TimeZoneInfo:

           // DateTime.Now fast path that avoids allocating an historically accurate TimeZoneInfo.Local and just creates a 1-year (current year) accurate time zone
            static internal TimeSpan GetDateTimeNowUtcOffsetFromUtc(DateTime timeout Boolean isAmbiguousLocalDst) {
                Boolean isDaylightSavings = false;
    #if FEATURE_WIN32_REGISTRY
                isAmbiguousLocalDst = false;
                TimeSpan baseOffset;
                int timeYear = time.Year;
     
                OffsetAndRule match = s_cachedData.GetOneYearLocalFromUtc(timeYear);
                baseOffset = match.offset;
     
                if (match.rule != null) {
                    isDaylightSavings = GetIsDaylightSavingsFromUtc(time, timeYear, match.offset, match.rule, out isAmbiguousLocalDst);
                    baseOffset += (isDaylightSavings ? match.rule.DaylightDelta : TimeSpan.Zero /* */);                
                }                
                return baseOffset;          
    #else
                // Use the standard code path for the Macintosh since there isn't a faster way of handling current-year-only time zones
                return GetUtcOffsetFromUtc(timeTimeZoneInfo.Localout isDaylightSavingsout isAmbiguousLocalDst);
    #endif // FEATURE_WIN32_REGISTRY
            }


    The program enters in  "if (match.rule != null)" and it ends up throwing an exception at (see CallStack from my first question):

    // Returns the DateTime resulting from adding a fractional number of
        // time units to this DateTime.
        private DateTime Add(double valueint scale) {
            long millis = (long)(value * scale + (value >= 0? 0.5-0.5));
            if (millis <= -MaxMillis || millis >= MaxMillis) 
                throw new ArgumentOutOfRangeException("value"Environment.GetResourceString("ArgumentOutOfRange_AddValue"));
            return AddTicks(millis * TicksPerMillisecond);
        }

      In addition, we have tried turning off "automatically adjust clock for Daylight Saving Time", according the last suggestion of this link:

    http://forum.fs-net.de/index.php/Thread/2887-ArgumentOutOfRangeExcetion-DateTime-Now/

    When turning off AutoDST, the program does not enter in  "if (match.rule != null)" and we work around the problem. The matter is that we have to supply this software to several clients and maybe this solution is not the best for them :).  

    Nevertheless, maybe it could be a clue to find a better solution.

    Thank you all for your support. 


      


    • Edited by huanlui Thursday, December 18, 2014 10:21 AM
    • Marked as answer by Fred BaoModerator Monday, December 29, 2014 8:55 AM
    Thursday, December 18, 2014 10:01 AM
  • Yes, jdweng, we have tried it by checking out the solution from svn into an empty folder and compiling it again, but the result is the same.

    Anyway, Thank you for your advice.  It could have been a good point. 

     

    Thursday, December 18, 2014 10:24 AM