如何在C++中将无符号的 int 64 转换为时间

How to convert unsigned int 64 into time in C++?

本文关键字:int 转换 时间 无符号 C++      更新时间:2023-10-16

我正在将 CLI C++代码转换为标准C++,我有一段代码获取 UINT64 编号(来自远程服务器 - 所以我无法更改为我获得的时间的格式/精度(并将其转换为 DateTime 对象,稍后输出以下值:myDatetime.ToString("dd/MM/yyyy hh:mm:ss.fffffff tt"(。我还没有找到将无符号的 int 64 转换为 C++ 时间的方法。以下代码对这么大的数字(这是我从服务器获得的 64 位数字(没有任何作用。

time_t rawtime=131274907755873979
localtime_s(&timeinfo, &rawtime);

我需要一些帮助:)

我的问题在线程中没有得到回答 将纪元时间字符串转换为时间 因为它不适用于我需要的大数字。例如,数字131274907755873979这是我从服务器得到的。该值的函数 ctime 仅返回 NULL。我需要一种方法来将我作为无符号 int64 获得的时间转换为标准C++时间对象。

std::string LongToString(int64_t longDate) {        
    char buff[128];
    std::chrono::duration<int64_t, std::milli> dur(longDate);
    auto tp = std::chrono::system_clock::time_point(
        std::chrono::duration_cast<std::chrono::system_clock::duration>(dur));
    std::time_t in_time_t = std::chrono::system_clock::to_time_t(tp);
    strftime(buff, 128, "%Y-%m-%d %H:%M:%S", localtime(&in_time_t));
    std::string resDate(buff);
    
    return resDate;
}

bsoncxx::types::b_date get_date((.to_int64(( MongoDB就是这种情况。

与int64_t一起保存的日期时间。

您还没有告诉我们现有代码如何将该数字转换为DateTime。 让我们假设它通过调用这个构造函数来做到这一点:DateTime( long long ticks )

根据日期时间构造函数的文档

长时钟周期 以自公历 0001 年 1 月 1 日 00:00:00.000 开始的 100 纳秒间隔数表示的日期和时间。

另一方面,根据localtime_s的文件time_t的文件localtime_s()需要

自 UTC 时间 1970 年 1 月 1 日 00:00 以来的秒数(不包括闰秒(。

因此,您首先需要将 100 纳秒间隔转换为秒,然后从 0001 年 1 月 1 日转换为 1970 年 1 月 1 日。

使用 Howard Hinnant 的日期时间库,这个计算可以很容易地完成。 它适用于VS 2013及更高版本。

#include "tz.h"
#include <cstdint>
#include <string>
#include <iostream>
std::string
FILETIME_to_string(std::uint64_t i)
{
    using namespace std;
    using namespace std::chrono;
    using namespace date;
    using FileTime = duration<int64_t, ratio<1, 10000000>>;
    auto const offset = sys_days{jan/1/1970} - sys_days{jan/1/1601};
    auto tp = sys_days{jan/1/1970} + (FileTime{static_cast<int64_t>(i)} - offset);
    return format("%d/%m/%Y %I:%M:%S %p", make_zoned("Etc/GMT-2", tp));
}
int
main()
{
    std::cout << FILETIME_to_string(131274907755873979) << 'n';
}

这会跳过DateTime,直接进入string。 我不确定你想要什么格式的tt。 但不管是什么,它都可以处理。

此库基于 C++11 <chrono>库构建。 因此,首先要做的是创建一个持续时间来表示窗口刻度大小(100 ns(。 然后只需计算两个纪元之间的偏移量并从输入中减去它,并形成一个std::chrono::time_point。 现在,您可以根据需要设置该time_point格式。

上面的程序输出:

29/12/2016 03:12:55.5873979 PM

如果您使用VS 2017,您将能够使offset constexpr,使转换更有效。