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

Dmi*_*ruk 8 .net c++ datetime boost

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

更新:确实需要使用C++; 我不能使用C++/CLI.

Mar*_*ius 5

  • 在.Net日期时间从01.01.01 00:00:00开始
  • 在boost ptime从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;
}
Run Code Online (Sandbox Code Playgroud)

//输出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;
}
Run Code Online (Sandbox Code Playgroud)