如何在现代C ++中将double转换为日期时间 [英] How to convert in modern C++ a double into a datetime

查看:821
本文介绍了如何在现代C ++中将double转换为日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在现代C ++(C ++ 11/14/17)中将 double 转换为使用

How to convert in modern C++ (C++11/14/17) a double into a date time using the date.h library, when the double has been generated while exporting an Excel worksheet as a CSV file?

例如,日期时间出现在Excel中:

For instance, the datetime appearing in Excel:

21/08/2017 11:54

21/08/2017 11:54

已被Excel转换为CSV文件的两倍:

has been converted by Excel into the CSV file as the double:

42968.4958333333

42968.4958333333

谢谢.

在11/07/2019上编辑:该问题与的使用有关. date.h 库.指出为可能重复"的其他问题不需要使用此库(另请参见 date.h 库作者在下面的评论)

EDIT on 11/07/2019: This questions is about the use of the date.h library. The other questions pointed out as "possible duplicates" does not require the use of this library (see also the comment below by the author of the date.h library)

推荐答案

使用 date.h ,看起来可能像这样:

Using date.h, it could look like this:

#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';
}

输出:

2017-08-21 11:54:00.000000

此定义假定您从42968.4958333333到21/08/2017 11:54的映射是正确的.我在另一个地方看到那个时代应该是1899-12-31,而不是1899-12-30.无论如何,一旦找到正确的纪元,这就是执行计算的方式.

This definition assumes that your mapping from 42968.4958333333 to 21/08/2017 11:54 is correct. I see in one other place that the epoch is supposed to be 1899-12-31, not 1899-12-30. In any event, once the correct epoch is found, this is how one would perform the computation.

啊, https://en.wikipedia.org/wiki/Leap_year_bug 解释了一对一的错误.为了与Lotus 1-2-3向后兼容,Excel的作者特意将1900年定为leap年.

Ah, https://en.wikipedia.org/wiki/Leap_year_bug explains the off-by-one error. The writers of Excel purposely considered 1900 a leap year for the purpose of backwards compatibility with Lotus 1-2-3.

此输出是在system_clock::durationmicroseconds的macOS上生成的.在system_clock::duration具有其他单位的其他平台上,输出将略有不同.

This output was generated on macOS where system_clock::duration is microseconds. The output will be slightly different on other platforms where system_clock::duration has other units.

另外:在此范围内,IEEE 64位double的精度比nanoseconds粗,但比microseconds细(约为microsecond的一半).

Aside: At this range, the precision of an IEEE 64 bit double is coarser than nanoseconds but finer than microseconds (on the order of half of microsecond).

这篇关于如何在现代C ++中将double转换为日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆