2012-03-25 59 views
7

我想使用C++/Boost来分析时间字符串,如1980.12.06 21:12:04.232,并获取对应于滴答计数(用于初始化)的ticks值。 NET的System.DateTime)。我该怎么做?Boost解析日期/时间字符串并产生与.NET兼容的Ticks值

更新:需要使用C++;我无法使用C++/CLI进行此操作。

+0

刚刚意识到,你是否真的*使用.NET,或者你只是希望它的价值与.NET提供的价值相同,而实际上却没有*使用* .NET? – casperOne 2012-03-25 23:28:16

回答

4
    在.net日期时间
  • 从01.01.01 00:00:00
  • 开始升压的ptime从1400年1月1日开始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; 
} 
0

.Net的“Ticks”间隔为100纳秒。

ticksType:00:在 00 System.Int64日期和时间,自1月1日起已经过 100纳秒的时间间隔,0001数表示在00.000公历日历

所以你需要一个已知时代(例如Unix纪元)的滴答计数,时代与期望的日期/时间之间的天数和一天中的时间(the total_nanoseconds accessor可能有所帮助)。然后,您可以使用简单的加法和乘法轻松计算.Net等效计数器计数。

您可能仍然遇到可代表的日期范围问题。