ste*_*gua 2 c++ excel c++20 excel-dates
在将 Excel 工作表导出为 CSV 文件时生成双精度值时,如何使用date.h库在现代 C++ (C++11/14/17) 中将双精度值转换为日期时间?
例如,Excel 中显示的日期时间:
2017年8月21日 11:54
已被 Excel 转换为 CSV 文件,如下所示:
42968.4958333333
谢谢。
编辑于 11/07/2019:这个问题是关于date.h库的使用。指出“可能重复”的其他问题不需要使用该库(另请参阅date.h库的作者下面的评论)
使用date.h,它可能看起来像这样:
#include "date/date.h"
#include <iostream>
std::chrono::system_clock::time_point
to_chrono_time_point(double d)
{
using namespace std::chrono;
using namespace date;
using ddays = duration<double, days::period>;
return sys_days{December/30/1899} + round<system_clock::duration>(ddays{d});
}
int
main()
{
using date::operator<<;
std::cout << to_chrono_time_point(42968.495833333333333333333) << '\n';
}
Run Code Online (Sandbox Code Playgroud)
其输出:
2017-08-21 11:54:00.000000
Run Code Online (Sandbox Code Playgroud)
此定义假设您从 42968.4958333333 到 21/08/2017 11:54 的映射是正确的。我在另一处看到纪元应该是 1899-12-31,而不是 1899-12-30。无论如何,一旦找到正确的纪元,这就是执行计算的方式。
啊,https://en.wikipedia.org/wiki/Leap_year_bug解释了差一错误。Excel 的编写者故意将 1900 年视为闰年,以便向后兼容 Lotus 1-2-3。
此输出是在 macOS 上生成的,system_clock::duration其中microseconds. 在具有其他单位的其他平台上,输出会略有不同system_clock::duration。
旁白:在此范围内,IEEE 64 位的精度double比 更粗nanoseconds,但比 更精细microseconds(大约是 的一半microsecond)。