需要帮助将Delphi时间转换为.NET时间

mrfwxfqh  于 2022-09-21  发布在  .NET
关注(0)|答案(4)|浏览(159)

我在将Delphi应用程序移植到C#时遇到了一个问题。Delphi应用程序将时间记录到日志文件中,然后将其读回程序中。但它记录的时间格式让我感到困惑。我找不到.Net库来正确转换它。

Delphi在日志文件中记录的时间:976129709(在Delphi代码中转换为1/14/20095:53:26 PM)

//Here is the Delphi code which records it: 
IntToStr(DirInfo.Time);

//Here is the Delphi code which reads it back in:
DateTimeToStr(FileDateToDateTime(StrToInt(stringTime));

有人知道我如何在.Net上阅读这篇文章吗?

0wi1tuuw

0wi1tuuw1#

Delphi的TSearchRec.Time格式是旧的DOS 32位日期/时间值。据我所知,没有内置的转换器,所以你得写一个。例如:

public static DateTime DosDateToDateTime(int DosDate)
{
     Int16 Hi = (Int16)((DosDate & 0xFFFF0000) >> 16);
     Int16 Lo = (Int16)(DosDate & 0x0000FFFF);

     return new DateTime(((Hi & 0x3F00) >> 9) + 1980, (Hi & 0xE0) >> 5, Hi & 0x1F,
        (Lo & 0xF800) >> 11, (Lo & 0x7E0) >> 5, (Lo & 0x1F) * 2);
}
fsi0uk1n

fsi0uk1n2#

Here is description of different date/time formats(Delphi的原生TDateTime是OLE自动化日期格式)。据此,您需要System.DateTime.FromFileTime()System.DateTime.ToFileTime()+DosDateTimeToFileTime()FileTimeToDosDateTime()函数。实际上,这是分两步进行的转换。

kd3sttzy

kd3sttzy3#

我尝试了谷歌搜索和实验,从伪代码开始查找类似于Unix时代的内容。

var x = 976129709;
  var target = new DateTime(2009, 1, 14, 17, 53, 26);
  var testTicks = target.AddTicks(-x);     // 2009-01-14 17:51:48
  var testMs = target.AddMilliseconds(-x); // 2009-01-03 10:44:36
  var testS = target.AddSeconds(-x);       // 1978-02-08 22:44:57
  // No need to check for bigger time units
  // since your input indicates second precision.

你能确认你的输入是正确的吗?

看在《会飞的意大利面怪物》的份上,放弃你的12小时时间格式吧!;)

oknwwptz

oknwwptz4#

我玩这个游戏已经晚了,但我已经用了好几年了,而且效果很好。它将Delphi时间转换为Windows记号,然后将其转换为日期时间。

public static DateTime DelphiTimeToDateTime(this double delphiTime)
{
    // scale it to 100nsec ticks.  Yes, we could do this as one expression
    // but this makes it a lot easier to read.

    // delphitime *= 864000000000L

    delphiTime *= 24; // hours since Delphi epoch
    delphiTime *= 60; // minutes since epoch
    delphiTime *= 60; // seconds since epoch
    delphiTime *= 1000; // milliseconds since epoch
    delphiTime *= 1000; // microseconds since epoch
    delphiTime *= 10; // 100 nsec ticks since epoch

    // Now, delphiTime is the number of ticks since 1899/12/30

    long time = 599264352000000000L; // 1/1/0001 --> 1899/12/30

    time += (long)delphiTime;

    // These are all *local* times, sadly
    return new DateTime(time, DateTimeKind.Local);
}

相关问题