Main Site Documentation

DateTime trouble


#1
Hi all,

Lets consider the following code snippet which calculates the span of time 
between two interrups (Panda II, newest SDK):

    //Version 1
    private void InterruptHandler(uint Port, uint State, DateTime time)
    {
      try
      {
        unchecked
        {
           _NewTicks = Utility.GetMachineTime().Ticks;
           _Duration = (int)(_NewTicks - _StartTicks);
          ...
          ...
          _StartTicks = _NewTicks;
        }
      }
      catch
      {
        ...
        ...
      }

This code is completely independent from all time changes (e.g. Utility.SetLocalTime/TimeService.SetTimeZoneOffset),
but Utility.GetMachineTime().Ticks is the timestamp at processing time, not the interrupt time. 
Using the time parameter will be more accurate , so lets try:


    // Version 2
    private void InterruptHandler(uint Port, uint State, DateTime time)
    {
      try
      {
        unchecked
        {
           _NewTicks = time.Ticks;
           _Duration = (int)(_NewTicks - _StartTicks);
          ...
          ...
          _StartTicks = _NewTicks;
        }
      }
      catch
      {
        ...
        ...
      }


 The problem here: the code will fail if elsewhere  Utility.SetLocalTime/TimeService.SetTimeZoneOffset will be used, so lets try:


    // Version 3
    private void InterruptHandler(uint Port, uint State, DateTime time)
    {
      try
      {
        unchecked
        {
           _NewTicks = Utility.GetMachineTime().Ticks - (DateTime.Now - time.Ticks) .Ticks;
           _Duration = (int)(_NewTicks - _StartTicks);
          ...
          ...
          _StartTicks = _NewTicks;
        }
      }
      catch
      {
        ...
        ...
      }

 Provided that execution time of Utility.GetMachineTime().Ticks and DateTime.Now is a constant value, _Duration will be accurate.
 But this code fails too, e.g TimeService.SetTimeZoneOffset(120) will affect DateTime.Now , but not the time parameter.

 ( DateTime.Now - time.Ticks is about "02:00:00.000xxx") . 
 Please note , both DateTime.Now and time are marked as local time (DateTimeKind = Local).
 
 
 Why is time parameter's time always UTC? And if that is correct (i guess it is) , why DateTimeKind is not Utc?

 Is there a property ("offset")  inside the framework  , so we can count back machine ticks from time parameter' ticks  :  MachineTtick= time.Ticks - "offset" ?
 It would spare me some work to follow time changes / time zones / daylight-saving time..

 

 Thank you very much in advance

#2

sorry,

Version 3 should be:


...
_NewTicks = Utility.GetMachineTime().Ticks - (DateTime.Now - time) .Ticks;
...


#3

Have you try using


DateTime.UtcNow