如何在C++中将无符号的 int 64 转换为时间
How to convert unsigned int 64 into time in C++?
我正在将 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
,使转换更有效。
- 是否可以从int转换为enum类类型
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 是什么导致了这种使用三进制而不是短整型的有符号int到无符号int转换
- 将字符串中的 int 转换为字母;
- 主.cpp:18:20:错误:从"int*"转换为"int"会失去精度 [-fa
- 将非常大的 int 转换为双倍,在某些计算机上会损失精度
- 如何将矢量<int>转换为字符数组?
- C++ 无法从 const int* 转换为 const_iterator
- 我不断收到错误 C2440'=':无法从"int *(__cdecl *)(int *,int *,int,int)"转换为"int *
- 如何将 int[4] 转换为 std::array<int,4>?
- 如何将data[i].int转换为vaible
- 将 int 转换为字符串,然后连接另一个变量以创建完整扩展名,然后将其转换为 const_char*
- 将私有矩阵形式 int 转换为双 C++
- 无法将参数 1 从 'int' 转换为 'int &'
- 将 int 转换为字符串后始终得到 0
- isspace 函数的性能警告,从 int 转换为布尔值
- 将大 int 转换为浮点数,而不舍入 c++
- 错误:无法将'uint8* {aka unsigned int*}'转换为"常量emxArray_uint8_T*"?
- 将未签名的INT转换为BCD
- 在 C++ 中将 int 转换为双精度