【问题标题】:Boost parse date/time string and yield .NET-compatible Ticks valueBoost 解析日期/时间字符串并产生与 .NET 兼容的 Ticks 值
【发布时间】:2023-03-07 06:59:01
【问题描述】:

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

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

【问题讨论】:

  • 刚刚意识到,您是实际使用 .NET,还是只是希望值与 .NET 提供的值相同而没有实际使用 .NET?

标签: c++ .net datetime boost


【解决方案1】:
  • .Net 日期时间从 01.01.01 00:00:00 开始
  • in 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;
}

// 输出 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;
}

【讨论】:

    【解决方案2】:

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

    ticksType: System.Int64 以数字表示的日期和时间 自 0001 年 1 月 1 日以来经过的 100 纳秒间隔 公历00:00:00.000

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

    您可能仍然对可表示的日期范围有疑问。

    【讨论】:

      猜你喜欢
      • 2018-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多