提升解析日期/时间字符串并生成与.NET兼容的Ticks值

Boost parse date/time string and yield .NET-compatible Ticks value

本文关键字:NET Ticks 串并 日期 字符串 字符 时间      更新时间:2023-10-16

我想使用C++/Boost来解析时间字符串,如1980.12.06 21:12:04.232,并获取一个与刻度计数相对应的ticks值(用于初始化.NET的System.DateTime)。我该怎么做?

更新:Ido需要使用C++;对此,我无法使用C++/CLI。

  • in.Net日期时间从01.01.01 00:00:00开始
  • 升压时间从1400.01.01 00.00.00开始

//c++代码

#include <boost/date_time/posix_time/posix_time.hpp>
int main(int argc, char* argv[])
{
    using namespace boost::posix_time;
    using namespace boost::gregorian;
    //C# offset till 1400.01.01 00:00:00
    uint64_t netEpochOffset = 441481536000000000LL;
    ptime ptimeEpoch(date(1400,1,1), time_duration(0,0,0));
    //note: using different format than yours, you'll need to parse the time in a different way
    ptime time = from_iso_string("19801206T211204,232");
    time_duration td = time - netEpoch;
    uint64_t nano = td.total_microseconds() * 10LL;
    std::cout <<"net ticks = " <<nano + netEpochOffset;
    return 0;
}

//输出624805819242320000

在c#中测试

static void Main(string[] args)
{
    DateTime date = new DateTime(1400,1,1);
    Console.WriteLine(date.Ticks);
    DateTime date2 = new DateTime(624805819242320000L); //C++ output
    Console.WriteLine(date2);
            /*output
             * 441481536000000000
             * 6/12/1980 21:12:04
             * */
    return;
}

.Net的"Ticks"以100纳秒为间隔。

  • http://msdn.microsoft.com/en-us/library/z2xf7zzk.aspx

ticksType:System.Int64日期和时间,用自0001年1月1日起在公历00:00:00.000

因此,您需要已知历元(例如Unix历元)的刻度计数、历元与所需日期/时间之间的天数以及一天中的时间(the total_nanoseconds accessor可能会有所帮助)。然后,您可以通过简单的加法和乘法,轻松地计算.Net等效的蜱虫计数。

您可能仍有与可表示日期范围有关的问题。