1

我正在使用一个没有真正记录的 C++ api 的包装器。一些公开的方法需要 uint 类型的字段(from 和 to)。这些字段实际上是 datefrom 和 dateto,但类型不是这样。我尝试了不同的方法,包括将 datetime 转换为 DOS unsigned int 表示

 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);
    }

,但如果不是错误,api函数调用仍然没有返回任何内容。,我还尝试了简单的表示形式:20160101,这是有道理的,但没有成功。有没有一种将日期和时间表示为无符号整数的已知方法?

4

2 回答 2

2

我制作了这个函数,我在从 API 获取的日期作为 uint 进行了测试。

    public DateTime FromCtmToDateTime(uint dateTime)
    {
        DateTime startTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
        return startTime.AddSeconds(Convert.ToDouble( dateTime));
    }

@ChrisF:我试过这个,它奏效了。这确实是 C 时间,这意味着开始日期是 1970 年午夜 - 1 -1;uint 表示自该日期以来的秒数。

通过处理从工作函数中获得的输出日期,我成功地获得了有意义的日期,并使用以下方法进行了相反的转换:

   public  UInt32 ToDosDateTime( DateTime dateTime)
    {
        DateTime startTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
        TimeSpan currTime = dateTime - startTime;
        UInt32 time_t = Convert.ToUInt32(Math.Abs(currTime.TotalSeconds));
        return time_t;
    }
于 2016-02-10T12:30:35.580 回答
1

.NET 本身存储DateTime为无符号长整数,表示从 0001 年 1 月 1 日开始的滴答声。从参考来源

// 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;

此外,UNIX 存储时间略有不同。根据维基百科

定义为自 1970 年 1 月 1 日星期四 00:00:00 协调世界时 (UTC) 以来经过的秒数

所以这可以很容易地用无符号整数表示。您可以将其转换为DateTime 没有太多代码的 a 。

于 2016-02-10T11:51:22.957 回答