c++ - Boost 解析日期/时间字符串并产生 .NET 兼容的 Ticks 值

标签 c++ .net datetime boost

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

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

最佳答案

  • 在 .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;
}

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

关于c++ - Boost 解析日期/时间字符串并产生 .NET 兼容的 Ticks 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9864339/

相关文章:

java - jOOQ 中按日历周分组

c++ - SetupDiEnumDeviceInterfaces 失败问题

.net - 缺少 Type.GetMember 和 MemberInfo.GetCustomAttributes (C# PCL .NET 4.6)

.net - Http 和文件上传 - 它是如何工作的(幕后)

c# - 如何检查 Java 中是否已经过了 X 秒?

jquery - 将字符串转换为时间对象

c++ - 将 Boost 正确安装到 Qt 中(当前失败,权限被拒绝)

c++ - 转发模板参数的常量性,我应该使用转发引用吗?

c++ - 从 Java 迁移到 C++ 和 new-operator

.net - 在 Entity Framework 事务中使用 SqlConnection