Search code examples
c#datetimetype-conversionuint

Date/Datetime as uint in wrapped api


I am using a wrapper of a C++ api which isn't really documented. Some of the exposed methods require fields (from and to) which are of type uint. The fields are actually datefrom and dateto, but the types aren't as such. I have tried different approaches, including converting datetime to DOS unsigned int representation

 public  ushort ToDosDateTime( DateTime dateTime)
    {
        uint day = (uint)dateTime.Day;              // Between 1 and 31
        uint month = (uint)dateTime.Month;          // Between 1 and 12
        uint years = (uint)(dateTime.Year - 1980);  // From 1980

        if (years > 127)
            throw new ArgumentOutOfRangeException("Cannot represent the year.");

        uint dosDateTime = 0;
        dosDateTime |= day << (16 - 16);
        dosDateTime |= month << (21 - 16);
        dosDateTime |= years << (25 - 16);

        return unchecked((ushort)dosDateTime);
    }

, but still the api function call returned nothing if not an error. , I also tried the plain representation as : 20160101 which made sense but didn't succeed. Is there a known way of representing dates and times as unsigned integers?


Solution

  • .NET itself stores DateTime as an unsigned long, representing the ticks from 1/1/0001. From the reference source:

    // The data is stored as an unsigned 64-bit integeter
    //   Bits 01-62: The value of 100-nanosecond ticks where 0 represents 1/1/0001 12:00am, up until the value
    //               12/31/9999 23:59:59.9999999
    //   Bits 63-64: A four-state value that describes the DateTimeKind value of the date time, with a 2nd
    //               value for the rare case where the date time is local, but is in an overlapped daylight
    //               savings time hour and it is in daylight savings time. This allows distinction of these
    //               otherwise ambiguous local times and prevents data loss when round tripping from Local to
    //               UTC time.
    private UInt64 dateData;
    

    Also, UNIX stores the time a little different. According to Wikipedia:

    defined as the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970

    So that can be expressed in an unsigned integer quite easily. You can convert that to a DateTime with not too much code.