2012-03-25 58 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等效計數器計數。

您可能仍然遇到可代表的日期範圍問題。